javascript - Event binding on dynamically created elements

Mots clés : javascriptjqueryeventsunobtrusive-javascriptjavascript

meilleur 5 Réponses javascript - Event binding on dynamically created elements

vote vote

90

$(staticAncestors).on(eventName, dynamicChild, function() {}); 
$(selector).live( eventName, function(){} ); 
$(selector).live( eventName, function(){} ); 
$(document).on( eventName, selector, function(){} ); 
$(document).on('mouseover mouseout', '.dosomething', function(){     // what you want to happen when mouseover and mouseout      // occurs on elements that match '.dosomething' }); 
$('.buttons').on('click', 'button', function(){     // do something here }); 
<div class="buttons">     <!-- <button>s that are generated dynamically and added here --> </div> 
vote vote

89

$("#dataTable tbody tr").on("click", function(event){     console.log($(this).text()); }); 
$("#dataTable tbody").on("click", "tr", function(event){     console.log($(this).text()); }); 
vote vote

71

document.addEventListener('click', function (e) {     if (hasClass(e.target, 'bu')) {         // .bu clicked         // Do your thing     } else if (hasClass(e.target, 'test')) {         // .test clicked         // Do your other thing     } }, false); 
function hasClass(elem, className) {     return elem.className.split(' ').indexOf(className) > -1; } 
function hasClass(elem, className) {     return elem.classList.contains(className); } 
function hasClass(elem, className) {   return elem.classList.contains(className); }  document.addEventListener('click', function(e) {   if (hasClass(e.target, 'bu')) {     alert('bu');     document.querySelector('.bu').innerHTML = '<div class="bu">Bu<div class="tu">Tu</div></div>';   } else if (hasClass(e.target, 'test')) {     alert('test');   } else if (hasClass(e.target, 'tu')) {     alert('tu');   }  }, false);
.test, .bu, .tu {   border: 1px solid gray;   padding: 10px;   margin: 10px; }
<div class="test">Test   <div class="bu">Bu</div>test </div>
vote vote

67

var mouseOverHandler = function() {     // Do stuff }; var mouseOutHandler = function () {     // Do stuff };  $(function() {     // On the document load, apply to existing elements     $('select').hover(mouseOverHandler, mouseOutHandler); });  // This next part would be in the callback from your Ajax call $("<select></select>")     .append( /* Your <option>s */ )     .hover(mouseOverHandler, mouseOutHandler)     .appendTo( /* Wherever you need the select box */ ) ; 
vote vote

53

function addCallbacks(eles){     eles.hover(function(){alert("gotcha!")}); }  $(document).ready(function(){     addCallbacks($(".myEles")) });  // ... add elements ... addCallbacks($(".myNewElements")) 

Questions similaires