动态地添加元素不触发动画 [英] Dynamically added elements don't trigger the animation

查看:138
本文介绍了动态地添加元素不触发动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的插件某些元素将关闭边栏。例如,如果在侧边栏有一个列表:

In my plugin some elements will close the sidebar. For example if in a sidebar there is a list:

<ul>
    <li>element 1</li>
    <li>element 2</li>
    <li>element 3</li>
</ul>

元素将触发关闭动画。
我的问题是,如果一些元素被异步加载,该插件将无法看到这些元素和动画不会被触发。
这不仅仅是 AJAX 我说的是加载的所有的元素动态

li elements will trigger the closing animation. My issue is that if some elements are loaded asynchronously, the plugin won't "see" those elements and the animation won't be triggered. It's not just AJAX I'm talking about all elements loaded dynamically!

在code是真的简单,这里有一个例子:

The code is really simple and here there is an example:

var $elements = 'li';

$elements.click(function() {
    $sidebar.animate({
        //animation
    });
});

如何才能让这些元素可见的插件?

How can I make those elements visible to the plugin?

下面的完整code https://开头的github .COM / dcdeiv /简单侧边栏/ BLOB /主/ jquery.simplesidebar.js

Here the complete code https://github.com/dcdeiv/simple-sidebar/blob/master/jquery.simplesidebar.js

推荐答案

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

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>

这篇关于动态地添加元素不触发动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆