开发者

jquery click without being attached to the DOM

var html = '<div><a href="#" id="test">Btn</a></div>';
$(html).find("#test").click(function(){
  console.log("clicked");
开发者_开发知识库});
//later
$(htmlNode).html(html);

Why don't I receive the "clicked" log?


You need to append the jQuery object, rather than just setting the inner HTML:

var html = $('<div><a href="#" id="test">Btn</a></div>');
html.find("#test").click(function(){
  console.log("clicked");
});
//later
$(htmlNode).append(html);

EDIT: Use append instead of html to be more clear, even though html seems to functionally equivalent to .empty().append(val) when passing in a jQuery object.


you are only attaching the click event to the html..you are not actually firing off the click event

try calling .click() after you attach the event.


It should be:

$(htmlNode).html(html).filter("#test").click(function(){
  console.log("clicked");
});

Or you can do:

$("#test").live('click',function(){
    console.log("clicked");
});

And create your html later


The issue is that you're binding a click event to something that isn't in the DOM yet and isn't a jQuery object. You can take two approaches.

1) Use Live:

$("#test").live('click', function(){
  console.log("clicked");
});
//later
var html = '<div><a href="#" id="test">Btn</a></div>';
$(htmlNode).html(html);

2) Construct a proper jQuery DOM object, and bind to that.

var a = $('<a></a>').attr('href', '#').click(function() {
  console.log("clicked");
});
//later
$(htmlNode).html(a.wrap('<div></div>').html()); //This could also use append or appendTo.

The best approach depends on your situation. Be sure to consider that appends to the DOM are very expensive in JavaScript!


Like above you are trying to add a click event to a dom element that doesn't yet exist.

$.live is an ok option but unfortunately a pain to maintain in large applications and is rather slow.

You can wrap the event binding in a timeout which pushes the event binding to the end of the queue - which means the event biding will execute AFTER you push your new elements to the dom. Like this:

var html = '<div><a href="#" id="test">Btn</a></div>';
setTimeout(function(){$("#test").click(function(){
  console.log("clicked");
});},0);
//later
$(htmlNode).html(html);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜