JQuery access dynamically created objects

天涯浪子 提交于 2019-12-02 11:54:00

.click() functions that aren't working on spans or divs that are added later, you'll need to use .live()

$("#clicker2").live("click", function(){
  # do stuff to spans currently existing
  # and those that will exist in the future
});

Create the div explicity and assemble its attributes and events before you append it.

var $div = $('<div />').append('can you click on me?').attr('id', 'clicker2').click(function() {
alert('hurray, it works');
});
$('#container').append($div);

Just put the click binding inside the first click function:

$('#click_me').click(function() 
{
    $('#container').append('<div id="clicker2">can you click on me?</div>');
    $('#clicker2').click(function(){  alert('hurray, it works');   });
});

As you have it, the binding is being called, but there is no "div#clicker2" to bind to the second function.

Hope this helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!