jQuery .click() not functioning

2019-08-14 06:00发布

I have built a <ul> list and it is being populated with <li id="subsitem"> from a jQuery function. I am trying to build a click function so that whenever one of those <li>'s is clicked, it disappears. I'm using the slideUp() function.

Here is my code:

$("#subsitem").click(function() {
  // Act on the event
  $(this).slideUp();
}); 

This doesn't work, yet when i change it to

$("li").click(function() {
  // Act on the event
  $(this).slideUp();
}); 

It works, but the only problem then is it works on all my <li>s. Anyone any tips?


update

Here is the code that is being used inside an .each()

$("#subs").append("<li><a href='#' class='subsitem'><div class='favicon'><img src='icon.png' width='16' height='16'></div>title</a></li>");

标签: jquery click
3条回答
Root(大扎)
2楼-- · 2019-08-14 06:13

What about doing something like:

$("#subsitem").click(function(){
    $(this).parent().slideUp();
});

To bind it to the parent <li> of the <a> that is clicked.

查看更多
Root(大扎)
3楼-- · 2019-08-14 06:20

Ok having used the jquery irc channel i managed to get the answer i was looking for.

I needed to use the .live() function. This is what my code now looks like

$("#subsitem").live('click',function(){
$(this).parent().slideUp();});
查看更多
乱世女痞
4楼-- · 2019-08-14 06:32

The problem is the first one is identifying by ID, which should be unique. You can change it to a class, and add the class to each li, to make it work.

$(".subitem").click(function() {
    // Act on the event
    $(this).slideUp();
}); 
查看更多
登录 后发表回答