2014-07-03 223 views
0

我有一個部分,用戶可以通過輸入文本並單擊添加按鈕添加標籤。添加標籤後,它會顯示一個刪除按鈕,以便用戶可以添加或刪除標籤。我已經創建了JavaScript代碼,以允許用戶添加以下工作的標籤。但是,我不知道如何讓用戶在點擊刪除按鈕時刪除標籤。任何幫助,將不勝感激。刪除點擊按鈕

if($("#addTag").length>0){ 

    $("#addTag").click(function(){ 

     var tag = $("#tag").val() 
     var campaign_tags = JSON.parse($("#campaign_tags").val()) 

     if(tag==''){ 
      alert('no text added') 
     } 
     else{ 
      //add check to see if the tag is already added 
      if(jQuery.inArray(tag, campaign_tags)==-1) 
      { 

       var tag_html = "<div class='campaign_tags'><small>"+tag+"</small><div class='campaign_btn remove_tag'>x</div></div>" 

       $("#tag_container").append(tag_html) 

       //now add the tag to the array 
       campaign_tags.push(tag) 
       $("#campaign_tags").val(JSON.stringify(campaign_tags)) 

       //re-initialize the delete function 
       init_remove_tag() 

      } 


     } 
    }) 
} 

回答

1

下面的代碼將在您點擊刪除按鈕時被調用。它會發現campaign_tags股利並將其刪除。

$(document).on("click", ".remove_tag", function(){ 
    $(this).parents(".campaign_tags").remove(); 
}); 

EDIT

作爲@Blazemonger建議.closest()是一個更好的選擇

$(document).on("click", ".remove_tag",function(){ 
    $(this).closest(".campaign_tags").remove(); 
}); 
+0

['.closest()'](http://api.jquery.com/closest/ )將會是比['.parents()']更好的選擇(http://api.jquery.com/parents/) – Blazemonger

+1

[另一個小改進](http://learn.jquery.com/events/event-委託/)將目標'$('#tag_container')'(最接近的永久祖先),而不是'$(文檔)' – Blazemonger