开发者

Using JQuery to select links created by JQuery

So if a button is clicked on my site, a new link is generated:

<a name="2" class="cld">mylink</a>

Now, is there any way I can use a selector li开发者_开发问答ke

$('.cld') 

to select this link that wasn't there when the page loaded?

I guess it's possible to use onClick as an attribute in the link tag. If so, could you tell me how. If the link is clicked, it should remove a div from the DOM with the id 'div-nr', nr being the same as the name attribute in the link.

I guess it's not that hard, but I've been struggling with this for the past hour and I would really appreciate a solution to this problem. Thanks!


It depends on when you use the selector:

  • If you use it after the link was generated, you are fine.
  • If you want to bind an event handler before the link was generated, have a look at live() and delegate().


You can use .live() and .delegate() to handle events on current and future elements matching the selector, for example:

$('.cld').live("click", function() {
  $("#div-nr").remove();
});

Or with .delegate():

$('#containerID').delegate('.cld', 'click', function() {
  $("#div-nr").remove();
});


The best thing to do is to give all of your default links their own class, and the new ones a different class. Then select on the original class.


You could use jQuery live events.

A regular .click() won't work for dynamically generated entities.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜