最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery Hide after append - Stack Overflow

programmeradmin3浏览0评论

I am running a script that will append an element upon selecting it from a dropdown list, that bit all works fine and appends the item. The item appended includes a button that will hide the appended item when clicked. What I can't seem to get to work is the hide function. The code seems to work fine if I put the element in manually into the HTML and click the hide button but for some reason when appending it it doesn't work?

$('#addteammember').click(function() {
 var usernamevalue = $("#teammemberselected").val();
 var teammemberfullname = $('#teammemberselected option:selected').text();
  $('#teammemberlist').append("<li><input class='removeteam' type='button' value="+usernamevalue+" /><span class='listitem'>"+teammemberfullname+"</span></li>");
});


$('.removeteam').click(function () {
  $(this).hide();
});   

I am running a script that will append an element upon selecting it from a dropdown list, that bit all works fine and appends the item. The item appended includes a button that will hide the appended item when clicked. What I can't seem to get to work is the hide function. The code seems to work fine if I put the element in manually into the HTML and click the hide button but for some reason when appending it it doesn't work?

$('#addteammember').click(function() {
 var usernamevalue = $("#teammemberselected").val();
 var teammemberfullname = $('#teammemberselected option:selected').text();
  $('#teammemberlist').append("<li><input class='removeteam' type='button' value="+usernamevalue+" /><span class='listitem'>"+teammemberfullname+"</span></li>");
});


$('.removeteam').click(function () {
  $(this).hide();
});   
Share Improve this question asked May 30, 2012 at 9:44 rmasperormaspero 6332 gold badges12 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

It happens because you append the button dynamically but bind your click handler for already existing elements only. You can use this code instead:

$("#teammemberlist").on("click", ".removeteam", function () {
    $(this).hide();
}); 

Try live function.

$(".removeteam").live("click", function() {
$(this).hide();
});
发布评论

评论列表(0)

  1. 暂无评论