动态创建的元素上的事件绑定?

时间:2022-10-22 07:53:29

I have a bit of code where I am looping through all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouse on/off.

我有一段代码,在其中循环遍历页面上的所有选择框,并将.hover事件绑定给它们,以便在打开/关闭鼠标时对它们的宽度进行微调。

This happens on page ready and works just fine.

这发生在page ready上并正常工作。

The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.

我遇到的问题是,在初始循环之后通过Ajax或DOM添加的任何选择框都没有事件绑定。

I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.

我已经找到了这个插件(jQuery Live Query plugin),但是在我用插件向页面中添加另一个5k之前,我想看看是否有人知道这样做的方法,可以直接使用jQuery,也可以使用另一个选项。

23 个解决方案

#1


1757  

As of jQuery 1.7 you should use jQuery.fn.on:

对于jQuery 1.7,您应该使用jQuery.fn.on:

$(staticAncestors).on(eventName, dynamicChild, function() {});

Prior to this, the recommended approach was to use live():

在此之前,推荐的方法是使用live():

$(selector).live( eventName, function(){} );

However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

然而,live()在1.7中被弃用为on(),在1.9中被完全删除。生活()签名:

$(selector).live( eventName, function(){} );

... can be replaced with the following on() signature:

…可替换为以下on()签名:

$(document).on( eventName, selector, function(){} );

For example, if your page was dynamically creating elements with the class name dosomething you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document. Though bear in mind document may not be the most efficient option.

例如,如果你的页面是动态创建元素绑定事件的类名dosomething的父母已经存在(这是问题的核心,你需要绑定到的东西存在,不绑定到动态内容),这可能是(最简单的选项)文档。虽然记住文件可能不是最有效的选择。

$(document).on('mouseover mouseout', '.dosomething', function(){
    // what you want to happen when mouseover and mouseout 
    // occurs on elements that match '.dosomething'
});

Any parent that exists at the time the event is bound is fine. For example

在事件绑定时存在的任何父类都是可以的。例如

$('.buttons').on('click', 'button', function(){
    // do something here
});

would apply to

将适用于

<div class="buttons">
    <!-- <button>s that are generated dynamically and added here -->
</div>

#2


293  

There is a good explanation in the documentation of jQuery.fn.on.

jQuery.fn.on的文档中有一个很好的解释。

In short:

简而言之:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

事件处理程序只绑定到当前选定的元素;当您的代码调用.on()时,它们必须存在于页面上。

Thus in the following example #dataTable tbody tr must exist before the code is generated.

因此,在下面的示例中,在生成代码之前,必须存在#dataTable tbody tr。

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

If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.

如果新的HTML被注入到页面中,最好使用委托事件来附加事件处理程序,如下所述。

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:

委托事件的优势在于,它们可以处理稍后添加到文档中的后代元素的事件。例如,如果表存在,但是行是通过代码动态添加的,下面将处理它:

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

In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, the first code example attaches a handler to 1,000 elements.

除了处理尚未创建的后代元素上的事件的能力之外,委托事件的另一个优点是,当必须监视许多元素时,它们可以降低开销。在数据表中,在其tbody中有1,000行,第一个代码示例将处理程序附加到1,000个元素。

A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody).

委托事件方法(第二个代码示例)只将一个事件处理程序附加到一个元素,即tbody,而事件只需要在一个级别(从单击的tr到tbody)上冒泡。

Note: Delegated events do not work for SVG.

注意:委托事件对SVG不起作用。

#3


150  

This is a pure JavaScript solution without any libraries or plugins:

这是一个纯JavaScript解决方案,没有任何库或插件:

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);

where hasClass is

hasClass在哪里

function hasClass(elem, className) {
    return elem.className.split(' ').indexOf(className) > -1;
}

Live demo

现场演示

Credit goes to Dave and Sime Vidas

这是大卫和西梅·维达斯的功劳

Using more modern JS, hasClass can be implemented as:

使用更多的现代JS, hasClass可以实现为:

function hasClass(elem, className) {
    return elem.classList.contains(className);
}

#4


57  

You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.

您可以在创建对象时向对象添加事件。如果您在不同的时间向多个对象添加相同的事件,那么创建一个命名函数可能是正确的方法。

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 */ )
;

#5


38  

You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:

您可以简单地将事件绑定调用包装到函数中,然后调用它两次:一次在准备好的文档上,一次在添加新DOM元素的事件之后。如果这样做,您将希望避免在现有元素上绑定相同的事件两次,因此您需要解绑定现有的事件,或者(更好的)只绑定到新创建的DOM元素。代码是这样的:

function addCallbacks(eles){
    eles.hover(function(){alert("gotcha!")});
}

$(document).ready(function(){
    addCallbacks($(".myEles"))
});

// ... add elements ...
addCallbacks($(".myNewElements"))

#6


36  

Try to use .live() instead of .bind(); the .live() will bind .hover to your checkbox after the Ajax request executes.

尝试使用.live()而不是.bind();在Ajax请求执行之后,.live()将绑定.hover到您的复选框中。

#7


19  

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

您可以使用live()方法将元素(甚至是新创建的元素)绑定到事件和处理程序,如onclick事件。

Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:

下面是我编写的一个示例代码,您可以看到live()方法如何将选定的元素(甚至是新创建的元素)与事件绑定在一起:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>

    <body>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>

        <input type="button" id="theButton" value="Click" />
        <script type="text/javascript">
            $(document).ready(function()
                {
                    $('.FOO').live("click", function (){alert("It Works!")});
                    var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
                                                                                                         autoOpen: false,
                                                                                                         tite: 'Basic Dialog'
                                                                                                     });
                    $('#theButton').click(function()
                    {
                        $dialog.dialog('open');
                        return('false');
                    });
                    $('#CUSTOM').click(function(){
                        //$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
                        var button = document.createElement("input");
                        button.setAttribute('class','FOO');
                        button.setAttribute('type','button');
                        button.setAttribute('value','CLICKMEE');
                        $('#container').append(button);
                    });
                    /* $('#FOO').click(function(){
                                                     alert("It Works!");
                                                 }); */
            });
        </script>
    </body>
</html>

#8


16  

Event binding on dynamically created elements

Single element:

单一的元素:

$(document.body).on('click','.element', function(e) {  });

Child Element:

子元素:

 $(document.body).on('click','.element *', function(e) {  });

Notice the added *. An event will be triggered for all children of that element.

注意添加*。将为该元素的所有子元素触发一个事件。

I have noticed that:

我注意到:

$(document.body).on('click','.#element_id > element', function(e) {  });

It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.

它不再起作用了,但以前起过作用。我一直在使用来自谷歌CDN的jQuery,但是我不知道他们是否改变了它。

#9


14  

Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:

另一种解决方案是在创建元素时添加侦听器。不是把监听器放在身体里,而是在你创建它的那一刻把监听器放在元素里:

var myElement = $('<button/>', {
    text: 'Go to Google!'
});

myElement.bind( 'click', goToGoogle);
myElement.append('body');


function goToGoogle(event){
    window.location.replace("http://www.google.com");
}

#10


14  

I prefer using the selector and I apply it on the document.

我更喜欢使用选择器,我将它应用于文档。

This binds itself on the document and will be applicable to the elements that will be rendered after page load.

它将自己绑定到文档上,并将适用于页面加载后呈现的元素。

For example:

例如:

$(document).on("click", $(selector), function() {
    // Your code here
});

#11


9  

You can attach event to element when dynamically created using jQuery(html, attributes).

当使用jQuery(html、属性)动态创建时,可以将事件附加到元素。

As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn) can be used as a property of the object passed to the second parameter:

对于jQuery 1.8,任何jQuery实例方法(jQuery.fn方法)都可以作为传递给第二个参数的对象的属性:

function handleDynamicElementEvent(event) {
  console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
    html: $.map(Array(3), function(_, index) {
      return new Option(index, index)
    }),
    on: {
      change: handleDynamicElementEvent
    }
  })
  .appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

#12


8  

Take note of "MAIN" class the element is placed, for example,

注意元素所在的“MAIN”类,例如,

<div class="container">
     <ul class="select">
         <li> First</li>
         <li>Second</li>
    </ul>
</div>

In the above scenario, the MAIN object the jQuery will watch is "container".

在上面的场景中,jQuery将监视的主要对象是“容器”。

Then you will basically have elements names under container such as ul, li, and select:

然后,在容器(如ul、li和select)中基本会有元素名:

$(document).ready(function(e) {
    $('.container').on( 'click',".select", function(e) {
        alert("CLICKED");
    });
 });

#13


8  

you could use

您可以使用

$('.buttons').on('click', 'button', function(){
    // your magic goes here
});

or

$('.buttons').delegate('button', 'click', function() {
    // your magic goes here
});

these two methods are equivalent but have a different order of parameters.

这两种方法是等价的,但是参数的顺序不同。

see: jQuery Delegate Event

看:jQuery委托事件

#14


7  

Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists

当事件被绑定时存在的任何父类,如果您的页面使用class name按钮动态创建元素,您将把事件绑定到已经存在的父类

$(document).ready(function(){
  //Particular Parent chield click
  $(".buttons").on("click","button",function(){
    alert("Clicked");
  });  
  
  //Dynamic event bind on button class  
  $(document).on("click",".button",function(){
    alert("Dymamic Clicked");
  });
  $("input").addClass("button");  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
  <input type="button" value="1">
  <button>2</button>
  <input type="text">
  <button>3</button>  
  <input type="button" value="5">  
  </div>
<button>6</button>

#15


7  

Here is why dynamically created elements do not respond to clicks :

为什么动态创建的元素不响应单击:

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>

As a workaround, you have to listen to all clicks and check the source element :

作为一个解决方案,您必须侦听所有单击并检查源元素:

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>

This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)

这被称为“事件委托”。好消息,这是jQuery的内置特性:-)

var i = 11;
var body = $("body");
body.on("click", "button", function () {
  var letter = (i++).toString(36).toUpperCase();
  body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>

#16


5  

Try like this -

这样的尝试,

$(document).on( 'click', '.click-activity', function () { ... });

#17


3  

Use the .on() method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.

使用jQuery http://api.jquery.com/on/的.on()方法将事件处理程序附加到活动元素。

Also as of version 1.9 .live() method is removed.

同样,在版本1.9 .live()方法被删除。

#18


1  

More flexible solution to create elements and bind events (source)

创建元素和绑定事件(源)的更灵活的解决方案

// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});

//creating a dynamic button
 var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });

// binding the event
 $btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
    console.log('clicked');
 });

// append dynamic button to the dynamic container
$div.append($btn);

// add the dynamically created element(s) to a static element
$("#box").append($div);

Note: This will create an event handler instance for each element (may affect performance when used in loops)

注意:这将为每个元素创建一个事件处理程序实例(在循环中使用时可能会影响性能)

#19


1  

Bind the event to a parent which already exists:

将事件绑定到已经存在的父类:

$(document).on("click", "selector", function() {
    // Your code here
});

#20


0  

I was looking a solution to get $.bind and $.unbind working without problems in dynamically added elements.

我在寻找一个能得到美元的解决方案。绑定和美元。在动态添加的元素中不存在问题的解绑定工作。

As on() makes the trick to attach events, in order to create a fake unbind on those I came to:

正如on()所做的那样,附加事件,以便在我遇到的那些事件上创建一个伪解绑定:

const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );

// unbind the click
$('body').on('click', 'button.send', function(){} );

#21


0  

I prefer to have event listeners deployed in a modular function fashion rather than scripting a document level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.

我更喜欢以模块化的函数方式部署事件监听器,而不是编写文档级事件监听器。我喜欢下面的内容。注意,您不能用相同的事件侦听器重载一个元素,所以不要担心附加多个侦听器——只附加一个侦听器。

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
}

#22


0  

This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.

这是由事件委托完成的。事件将绑定到包装类元素上,但将委托给选择类元素。这就是它的工作原理。

$('.wrapper-class').on("click", '.selector-class', function() {
    // Your code here
});

Note: wrapper-class element can be anything ex. document, body or you wrapper. Wrapper should already exists.

注意:包装类元素可以是任何东西,例如文档、正文或包装器。包装应该已经存在。

#23


-1  

<html>
    <head>
        <title>HTML Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>

    <body>
        <div id="hover-id">
            Hello World
        </div>

        <script>
            jQuery(document).ready(function($){
                $(document).on('mouseover', '#hover-id', function(){
                    $(this).css('color','yellowgreen');
                });

                $(document).on('mouseout', '#hover-id', function(){
                    $(this).css('color','black');
                });
            });
        </script>
    </body>
</html>

#1


1757  

As of jQuery 1.7 you should use jQuery.fn.on:

对于jQuery 1.7,您应该使用jQuery.fn.on:

$(staticAncestors).on(eventName, dynamicChild, function() {});

Prior to this, the recommended approach was to use live():

在此之前,推荐的方法是使用live():

$(selector).live( eventName, function(){} );

However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

然而,live()在1.7中被弃用为on(),在1.9中被完全删除。生活()签名:

$(selector).live( eventName, function(){} );

... can be replaced with the following on() signature:

…可替换为以下on()签名:

$(document).on( eventName, selector, function(){} );

For example, if your page was dynamically creating elements with the class name dosomething you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document. Though bear in mind document may not be the most efficient option.

例如,如果你的页面是动态创建元素绑定事件的类名dosomething的父母已经存在(这是问题的核心,你需要绑定到的东西存在,不绑定到动态内容),这可能是(最简单的选项)文档。虽然记住文件可能不是最有效的选择。

$(document).on('mouseover mouseout', '.dosomething', function(){
    // what you want to happen when mouseover and mouseout 
    // occurs on elements that match '.dosomething'
});

Any parent that exists at the time the event is bound is fine. For example

在事件绑定时存在的任何父类都是可以的。例如

$('.buttons').on('click', 'button', function(){
    // do something here
});

would apply to

将适用于

<div class="buttons">
    <!-- <button>s that are generated dynamically and added here -->
</div>

#2


293  

There is a good explanation in the documentation of jQuery.fn.on.

jQuery.fn.on的文档中有一个很好的解释。

In short:

简而言之:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

事件处理程序只绑定到当前选定的元素;当您的代码调用.on()时,它们必须存在于页面上。

Thus in the following example #dataTable tbody tr must exist before the code is generated.

因此,在下面的示例中,在生成代码之前,必须存在#dataTable tbody tr。

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

If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.

如果新的HTML被注入到页面中,最好使用委托事件来附加事件处理程序,如下所述。

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:

委托事件的优势在于,它们可以处理稍后添加到文档中的后代元素的事件。例如,如果表存在,但是行是通过代码动态添加的,下面将处理它:

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

In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, the first code example attaches a handler to 1,000 elements.

除了处理尚未创建的后代元素上的事件的能力之外,委托事件的另一个优点是,当必须监视许多元素时,它们可以降低开销。在数据表中,在其tbody中有1,000行,第一个代码示例将处理程序附加到1,000个元素。

A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody).

委托事件方法(第二个代码示例)只将一个事件处理程序附加到一个元素,即tbody,而事件只需要在一个级别(从单击的tr到tbody)上冒泡。

Note: Delegated events do not work for SVG.

注意:委托事件对SVG不起作用。

#3


150  

This is a pure JavaScript solution without any libraries or plugins:

这是一个纯JavaScript解决方案,没有任何库或插件:

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);

where hasClass is

hasClass在哪里

function hasClass(elem, className) {
    return elem.className.split(' ').indexOf(className) > -1;
}

Live demo

现场演示

Credit goes to Dave and Sime Vidas

这是大卫和西梅·维达斯的功劳

Using more modern JS, hasClass can be implemented as:

使用更多的现代JS, hasClass可以实现为:

function hasClass(elem, className) {
    return elem.classList.contains(className);
}

#4


57  

You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.

您可以在创建对象时向对象添加事件。如果您在不同的时间向多个对象添加相同的事件,那么创建一个命名函数可能是正确的方法。

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 */ )
;

#5


38  

You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:

您可以简单地将事件绑定调用包装到函数中,然后调用它两次:一次在准备好的文档上,一次在添加新DOM元素的事件之后。如果这样做,您将希望避免在现有元素上绑定相同的事件两次,因此您需要解绑定现有的事件,或者(更好的)只绑定到新创建的DOM元素。代码是这样的:

function addCallbacks(eles){
    eles.hover(function(){alert("gotcha!")});
}

$(document).ready(function(){
    addCallbacks($(".myEles"))
});

// ... add elements ...
addCallbacks($(".myNewElements"))

#6


36  

Try to use .live() instead of .bind(); the .live() will bind .hover to your checkbox after the Ajax request executes.

尝试使用.live()而不是.bind();在Ajax请求执行之后,.live()将绑定.hover到您的复选框中。

#7


19  

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

您可以使用live()方法将元素(甚至是新创建的元素)绑定到事件和处理程序,如onclick事件。

Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:

下面是我编写的一个示例代码,您可以看到live()方法如何将选定的元素(甚至是新创建的元素)与事件绑定在一起:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>

    <body>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>

        <input type="button" id="theButton" value="Click" />
        <script type="text/javascript">
            $(document).ready(function()
                {
                    $('.FOO').live("click", function (){alert("It Works!")});
                    var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
                                                                                                         autoOpen: false,
                                                                                                         tite: 'Basic Dialog'
                                                                                                     });
                    $('#theButton').click(function()
                    {
                        $dialog.dialog('open');
                        return('false');
                    });
                    $('#CUSTOM').click(function(){
                        //$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
                        var button = document.createElement("input");
                        button.setAttribute('class','FOO');
                        button.setAttribute('type','button');
                        button.setAttribute('value','CLICKMEE');
                        $('#container').append(button);
                    });
                    /* $('#FOO').click(function(){
                                                     alert("It Works!");
                                                 }); */
            });
        </script>
    </body>
</html>

#8


16  

Event binding on dynamically created elements

Single element:

单一的元素:

$(document.body).on('click','.element', function(e) {  });

Child Element:

子元素:

 $(document.body).on('click','.element *', function(e) {  });

Notice the added *. An event will be triggered for all children of that element.

注意添加*。将为该元素的所有子元素触发一个事件。

I have noticed that:

我注意到:

$(document.body).on('click','.#element_id > element', function(e) {  });

It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.

它不再起作用了,但以前起过作用。我一直在使用来自谷歌CDN的jQuery,但是我不知道他们是否改变了它。

#9


14  

Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:

另一种解决方案是在创建元素时添加侦听器。不是把监听器放在身体里,而是在你创建它的那一刻把监听器放在元素里:

var myElement = $('<button/>', {
    text: 'Go to Google!'
});

myElement.bind( 'click', goToGoogle);
myElement.append('body');


function goToGoogle(event){
    window.location.replace("http://www.google.com");
}

#10


14  

I prefer using the selector and I apply it on the document.

我更喜欢使用选择器,我将它应用于文档。

This binds itself on the document and will be applicable to the elements that will be rendered after page load.

它将自己绑定到文档上,并将适用于页面加载后呈现的元素。

For example:

例如:

$(document).on("click", $(selector), function() {
    // Your code here
});

#11


9  

You can attach event to element when dynamically created using jQuery(html, attributes).

当使用jQuery(html、属性)动态创建时,可以将事件附加到元素。

As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn) can be used as a property of the object passed to the second parameter:

对于jQuery 1.8,任何jQuery实例方法(jQuery.fn方法)都可以作为传递给第二个参数的对象的属性:

function handleDynamicElementEvent(event) {
  console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
    html: $.map(Array(3), function(_, index) {
      return new Option(index, index)
    }),
    on: {
      change: handleDynamicElementEvent
    }
  })
  .appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

#12


8  

Take note of "MAIN" class the element is placed, for example,

注意元素所在的“MAIN”类,例如,

<div class="container">
     <ul class="select">
         <li> First</li>
         <li>Second</li>
    </ul>
</div>

In the above scenario, the MAIN object the jQuery will watch is "container".

在上面的场景中,jQuery将监视的主要对象是“容器”。

Then you will basically have elements names under container such as ul, li, and select:

然后,在容器(如ul、li和select)中基本会有元素名:

$(document).ready(function(e) {
    $('.container').on( 'click',".select", function(e) {
        alert("CLICKED");
    });
 });

#13


8  

you could use

您可以使用

$('.buttons').on('click', 'button', function(){
    // your magic goes here
});

or

$('.buttons').delegate('button', 'click', function() {
    // your magic goes here
});

these two methods are equivalent but have a different order of parameters.

这两种方法是等价的,但是参数的顺序不同。

see: jQuery Delegate Event

看:jQuery委托事件

#14


7  

Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists

当事件被绑定时存在的任何父类,如果您的页面使用class name按钮动态创建元素,您将把事件绑定到已经存在的父类

$(document).ready(function(){
  //Particular Parent chield click
  $(".buttons").on("click","button",function(){
    alert("Clicked");
  });  
  
  //Dynamic event bind on button class  
  $(document).on("click",".button",function(){
    alert("Dymamic Clicked");
  });
  $("input").addClass("button");  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
  <input type="button" value="1">
  <button>2</button>
  <input type="text">
  <button>3</button>  
  <input type="button" value="5">  
  </div>
<button>6</button>

#15


7  

Here is why dynamically created elements do not respond to clicks :

为什么动态创建的元素不响应单击:

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>

As a workaround, you have to listen to all clicks and check the source element :

作为一个解决方案,您必须侦听所有单击并检查源元素:

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>

This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)

这被称为“事件委托”。好消息,这是jQuery的内置特性:-)

var i = 11;
var body = $("body");
body.on("click", "button", function () {
  var letter = (i++).toString(36).toUpperCase();
  body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>

#16


5  

Try like this -

这样的尝试,

$(document).on( 'click', '.click-activity', function () { ... });

#17


3  

Use the .on() method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.

使用jQuery http://api.jquery.com/on/的.on()方法将事件处理程序附加到活动元素。

Also as of version 1.9 .live() method is removed.

同样,在版本1.9 .live()方法被删除。

#18


1  

More flexible solution to create elements and bind events (source)

创建元素和绑定事件(源)的更灵活的解决方案

// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});

//creating a dynamic button
 var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });

// binding the event
 $btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
    console.log('clicked');
 });

// append dynamic button to the dynamic container
$div.append($btn);

// add the dynamically created element(s) to a static element
$("#box").append($div);

Note: This will create an event handler instance for each element (may affect performance when used in loops)

注意:这将为每个元素创建一个事件处理程序实例(在循环中使用时可能会影响性能)

#19


1  

Bind the event to a parent which already exists:

将事件绑定到已经存在的父类:

$(document).on("click", "selector", function() {
    // Your code here
});

#20


0  

I was looking a solution to get $.bind and $.unbind working without problems in dynamically added elements.

我在寻找一个能得到美元的解决方案。绑定和美元。在动态添加的元素中不存在问题的解绑定工作。

As on() makes the trick to attach events, in order to create a fake unbind on those I came to:

正如on()所做的那样,附加事件,以便在我遇到的那些事件上创建一个伪解绑定:

const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );

// unbind the click
$('body').on('click', 'button.send', function(){} );

#21


0  

I prefer to have event listeners deployed in a modular function fashion rather than scripting a document level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.

我更喜欢以模块化的函数方式部署事件监听器,而不是编写文档级事件监听器。我喜欢下面的内容。注意,您不能用相同的事件侦听器重载一个元素,所以不要担心附加多个侦听器——只附加一个侦听器。

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
}

#22


0  

This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.

这是由事件委托完成的。事件将绑定到包装类元素上,但将委托给选择类元素。这就是它的工作原理。

$('.wrapper-class').on("click", '.selector-class', function() {
    // Your code here
});

Note: wrapper-class element can be anything ex. document, body or you wrapper. Wrapper should already exists.

注意:包装类元素可以是任何东西,例如文档、正文或包装器。包装应该已经存在。

#23


-1  

<html>
    <head>
        <title>HTML Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>

    <body>
        <div id="hover-id">
            Hello World
        </div>

        <script>
            jQuery(document).ready(function($){
                $(document).on('mouseover', '#hover-id', function(){
                    $(this).css('color','yellowgreen');
                });

                $(document).on('mouseout', '#hover-id', function(){
                    $(this).css('color','black');
                });
            });
        </script>
    </body>
</html>