2015-02-06 114 views
-1

我想创建类似stackoverflow.com标签云的东西。 我能够显示标签,但坚持如何捕获哪个标签元素取消按钮被点击。找到哪个动态创建的按钮已被点击

取消按钮是使用jquery动态创建的,点击btnAdd

$("#<%=btnAdd.ClientID%>").on('click',function(){ 
    var tagText = $('#<%=txtTag.ClientID%>').val(); 
    var btnCancel = '<button class="btn btn-default">X</button>'; 

    var tagTextDiv ='<div class="tagElement">' + tagText + btnCancel +'</div>'; 

    $("#divTagCloud").append(' ' + tagTextDiv); 
}); 

HTML是

<div class="col-xs-12 col-sm-6"> 
    <asp:TextBox runat="server" /> 
</div> 
<div class="col-xs-12 col-sm-6"> 
    <asp:Button runat="server" id="btnAdd"/> 
</div> 


<div class="col-xs-12 col-sm-12"> 
    <div id="divTagCloud"></div> 
</div> 

我想删除的标签即相应取消按钮的点击相应tagTextDiv

如何做到这一点?

+0

您能否为您的问题添加一个HTML结构示例。 – 2015-02-06 08:06:53

+0

好的给我一分钟 – 2015-02-06 08:07:22

+0

你能够显示jQuery的输出(在asp.net标签被渲染后?) – atmd 2015-02-06 08:09:27

回答

1

创建标记和按钮元素作为jQuery对象而不是字符串。这允许您在将事件处理程序插入DOM之前附加它们。

$("#<%=btnAdd.ClientID%>").on('click',function(){ 
    var tagText = $('#txtTag').val(); 
    // Create the tag and cancel button elements 
    var btnCancel = $('<button class="btn btn-default">X</button>'); 
    var tagTextDiv = $('<div class="tagElement">' + tagText + '</div>'); 
    // insert the cancel button into the tag element 
    tagTextDiv.append(btnCancel); 
    // attach an onclick event handler to the cancel button, that removes the tag. 
    btnCancel.click(function() { 
     // "this" is the element that the event handler is attached to, in this case, the cancel button 
     // get its' parent (the tag text div) and remove that from the DOM 
     $(this).parent().remove(); 
    }); 
    // finally, insert the new tag into the DOM 
    $("divTagCloud").append(tagTextDiv); 
});