2015-02-06 2 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 내가 취소 버튼을 해당의 클릭에 tagTextDiv 해당 즉 태그를 제거 할

<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> 

입니다.

어떻게 하시겠습니까?

+0

질문에 HTML 구조의 예를 추가해주십시오. –

+0

ok 분께 –

+0

asp.net 태그가 렌더링 된 후 jquery 출력을 볼 수 있습니까? – atmd

답변

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); 
}); 
관련 문제