繁体   English   中英

jQuery:在静态和动态创建的元素上进行某些操作(委托事件)

[英]jQuery: Doing something on a static and dynamically created elements (delegated events)

当我加载页面我有所谓的特殊类中的一些“静态”的HTML标签.file_item在容器调用#files_container 稍后在同一页面上,不进行刷新,而是通过Ajax new .file_item附加( .file_item )。 简单的$ .ajax-正常工作。

我的问题是,然后我想对这些元素执行on click事件。

我知道有什么问题- 我知道如何解决这个问题,但是我发现自己的方法极其丑陋。 我知道委托事件( http://api.jquery.com/on/#direct-and-delegated-events ),并且知道触发:

$('.file_item').click(function() {
    // will work on static elements but won't work on "dynamic" elements appended via Ajax.
});

$('#files_container').on('click', '.file_item', function() {
    // won't work on static elements but will work on "dynamic" elements appended via Ajax.
});

最后是我的问题:如何将两者结合在一起,那么无论我加载页面时是否存在.file_item还是15分钟后通过Ajax附加了.file_item ,括号内的代码都将执行?

编辑:

HTML的外观如下:

<section id="files_container">
    <section class="file_item">file 1</section>
    <section class="file_item">file 2</section>
    <section class="file_item">file 3</section>
    <section class="file_item">file 4</section>
    <section class="file_item">file 5</section>
</section>

其他文件将通过Ajax前置。

<section id="files_container">
    <section class="file_item">new one injected via prepend by $.ajax</section>
    <section class="file_item">file 1</section>
    <section class="file_item">file 2</section>
    <section class="file_item">file 3</section>
    <section class="file_item">file 4</section>
    <section class="file_item">file 5</section>
</section>

我认为问题在于静态元素不是files_container元素的后代,这就是为什么委托处理程序无法为其工作的原因。

因此,解决方案是在静态和动态元素之间找到一个公共父级,并将委托处理程序绑定到该父级。 由于您尚未共享标记,因此下面将处理程序绑定到应该处理两种情况的文档对象

$(document).on('click', '.file_item', function() {
    // your code here
});

只需使用您提供的第二个代码段即可。 它适用于静态和动态元素。 当存在静态和动态元素时,始终委托事件,而无需编写两个事件处理程序。 如果该代码对您不起作用,那么肯定有其他问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM