我正在尝试创建类似stackoverflow.com标签云的东西。 我能够显示标签,但仍然坚持如何捕获哪个标签元素取消按钮被点击。
单击btnAdd
时,使用jquery动态创建取消按钮。
$("#<%=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 :(得分: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);
});