为什么在附加元素上单击不起作用? [英] Why doesn't click work on appended elements?

查看:120
本文介绍了为什么在附加元素上单击不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to move some html elements from one container to another endlessly using jQuery append function but, the click event won't fire no more when I click on the element/s that have been appended.

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

Based on some threads similar to mine I found out that appended elements are stripped off of their event listeners. How can I avoid that, can someone show a solution ?

这是:小提琴

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

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

推荐答案

它将起作用.使用以下方法进行附加.

It will work. Use the following method for appended.

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

问题的说明,

执行以下操作,

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

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

An event handler is attached to all span elements that are currently on the page, while loading the page. You create new elements with every click. They have no handler attached. You can use

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

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

That will handle the clicks on the new elements as well.

这篇关于为什么在附加元素上单击不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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