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 */ );
function addCallbacks(eles){eles.hover(function(){alert("gotcha!")});}
$(document).ready(function(){addCallbacks($(".myEles"))});
// ... add elements ...addCallbacks($(".myNewElements"))
$(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>
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);
hasClass在哪里
function hasClass(elem, className) {return elem.className.split(' ').indexOf(className) > -1;}
var myElement = $('<button/>', {text: 'Go to Google!'});
myElement.bind( 'click', goToGoogle);myElement.append('body');
function goToGoogle(event){window.location.replace("http://www.google.com");}
var body = $("body");var btns = $("button");var btnB = $("<button>B</button>");// `<button>B</button>` is not yet in the document.// Thus, `$("button")` gives `[<button>A</button>]`.// Only `<button>A</button>` gets a click listener.btns.on("click", function () {console.log(this);});// Too late for `<button>B</button>`...body.append(btnB);
var body = $("body");var btnB = $("<button>B</button>");var btnC = $("<button>C</button>");// Listen to all clicks and// check if the source element// is a `<button></button>`.body.on("click", function (ev) {if ($(ev.target).is("button")) {console.log(ev.target);}});// Now you can add any number// of `<button></button>`.body.append(btnB);body.append(btnC);
var i = 11;var body = $("body");body.on("click", "button", function () {var letter = (i++).toString(36).toUpperCase();body.append($("<button>" + letter + "</button>"));});
var iterations = 4;var button;var body = document.querySelector("body");
for (var i = 0; i < iterations; i++) {button = document.createElement("button");button.classList.add("my-button");button.appendChild(document.createTextNode(i));button.addEventListener("click", myButtonWasClicked);body.appendChild(button);}
function myButtonWasClicked(e) {console.log(e.target); //access to this specific button}