且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态地添加元素不触发动画

更新时间:2022-11-28 16:36:54

动态元素不会触发回调,因为有绑定到这些动态元素没有事件侦听器。结果
如果你想处理事件元素不存在,或使用选择器将选择动态添加的元素,应该的代表的事件:

Dynamic elements don't trigger the callback, because there are no event listeners bound to those dynamic elements.
If you want to handle events to elements that don't exist yet, or using a selector that will select elements that are added dynamically, you should delegate the event:

$(document).on('click', 'li', function()
{
    //handle
});

这code结合对文档本身的点击监听器和回调会被调用为每一次点击注册,但元素是一个孩子元素上的侦听器是绑定的。例如:

This code binds a click listener on the document itself, and the callback will be invoked for every click that is registered, provided that li element is a child of the element on which the listener is bound. For example:

<div id='foo'>
    <div id='bar'>
        <span> test</span>
    </div>
    <span> test2</span>
</div>

考虑这个code:

Consider this code:

var outer = $('#foo');
$('#bar').on('click', 'span', function()
{
    outer.append($('<span>Added</span>'));
});

这将增加跨度栏元素中的跨度点击每次 div来。 DIV ID ='酒吧'&GT; 结果当您单击不属于&LT的孩子跨度它不会被调用
这code,但是:

This will add spans to the foo div every time the span inside the bar element is clicked. It will not be invoked when you click spans that aren't children of the <div id='bar'>
This code, however:

$('#foo').on('click', 'span', function()
{
    console.log(this);
});

将在点击反应的所有的跨越&LT内部; DIV ID ='富'&GT; 元素。动态和静态的一致好评,连 DIV中的跨度。

will react to clicks on all spans inside the <div id='foo'> element. Dynamic and static alike, even the span inside the bar div.

基本原则进行的拇指:阅读这些片段,像这样:

Basic rule-of-thumb: read these snippets like so:

$(document).on('click',   'div',    function(){});
  <scope>     <event>  <selector>   <callback>
on event in <scope> for elements matching <selector>, apply <callback>