【问题标题】:Why doesn't click work on appended elements?为什么单击对附加元素不起作用?
【发布时间】:2013-08-11 19:08:40
【问题描述】:

我想使用 jQuery append 函数将一些 html 元素从一个容器无休止地移动到另一个容器,但是当我单击已附加的元素时,单击事件不会再触发。

基于与我的类似的一些线程,我发现附加元素已从其事件侦听器中剥离。我该如何避免这种情况,有人可以提出解决方案吗?

这里是:Fiddle

    $('section.container-A div.elem').click(function() {
        $('section.container-B').append(this) ;
    }) ;

    $('section.container-B div.elem').click(function() {
        $('section.container-A').append(this) ;
    }) ;

【问题讨论】:

    标签: jquery jquery-click-event jquery-append


    【解决方案1】:

    它会起作用的。使用下面的方法追加。

     $(document).on('click', 'section.container-A div.elem', function() {
            $('section.container-B').append(this) ;
     }) ;
    

    问题的解释,

    执行以下操作,

    $("span").click(function(){
    

    在加载页面时,将事件处理程序附加到页面上当前的所有span 元素。每次点击都会创建新元素。他们没有附加处理程序。你可以使用

    $(document).on('click', 'span.class', function(...
    

    这也将处理对新元素的点击。

    【讨论】:

    • 如何在vanilla js中达到同样的效果?
    【解决方案2】:

    你需要使用.on()方法:

    $(document).on('click', 'section.container-1 div.elem', function() {
        var html = this;
        $('section.container-2').append(html) ;
    }) ;
    
    $(document).on('click', 'section.container-2 div.elem', function() {
        var html = this;
        $('section.container-1').append(html) ;
    }) ;
    

    小提琴:http://jsfiddle.net/x2A7n/16/

    【讨论】:

    • 我使用了您的代码,但似乎没有任何反应。是否有支持此 ON 功能的特定 jQuery 版本?我使用的是 1.9 及更高版本?谢谢
    • @twimB 抱歉,我已经更新了我的代码,忘记了$(document).on(),以及它的工作原理。
    • 显然它在 Opera 中不起作用。它确实适用于铬。非常感谢。
    【解决方案3】:

    我试过 here 并且成功了..

    这是代码,希望对你有帮助。

    $('section.container-1 div.elem').click(function() {     
        var a = $(this).text();     
        $('section.container-2').append('<div class=\'elem\'>' + a + '</div>') ;
    }) ;
    
    $('section.container-2 div.elem').click(function() {
        var a = $(this).text();
        $('section.container-1').append('<div  class=\'elem\'>' + a + '</div>') ;
    }) ;
    

    【讨论】:

      【解决方案4】:

      当您的页面中有多个 div 和多个类时,调用正确的 div 可能会很麻烦。 我通过将 id 添加到 div 找到并修复了它,jquery 也喜欢 find by id 和它的速度。您可以使用。

      $(document).on('click touchstart', 'div#the_id div.the_class', function(){
       //yourcode
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-11
        • 2011-05-25
        • 2019-04-28
        • 1970-01-01
        • 2023-02-15
        • 1970-01-01
        相关资源
        最近更新 更多