Why doesn't click work on appended elements?

北城以北 提交于 2019-12-04 14:18:33

It will work. Use the following method for appended.

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

Explanation of the problem,

Doing the following,

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

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.

You need to use the .on() method:

$(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) ;
}) ;

Fiddle: http://jsfiddle.net/x2A7n/16/

I tried it here and it worked..

Here is the code, hope it helps.

$('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>') ;
}) ;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!