<分区>
标签 javascript jquery html css
<分区>
html:
<div class="testSpanDiv"></div>
JavaScript:
$(document).ready(function () {
$('.testSpanDiv').append('<span id="testSpan">Hello</span>');
}
$('#testSpan').on('click', function(){
$(this).parent().remove();
});
点击动态添加的跨度元素时事件未触发。 如果将 span 元素静态添加到 html 中,则会触发事件。 你能对此提出任何建议吗?
我也像下面这样尝试过,但没有用。
$('#testSpan').on('click', '.testSpanDiv', function(){
$(this).parent().remove();
});
最佳答案
你需要这样使用:
$('.testSpanDiv').on('click', '#testSpan', function(){ // ^^ parent div ^^ element in which you want to bind the function $(this).parent().remove(); });
关于javascript - 如何为动态添加的跨度元素分配点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39115692/