javascript - 清除并附加 html 后单击不起作用

标签 javascript jquery html css

在我清除并使用 jquery 将 html 附加到 div 后,单击不起作用。 这是html代码

<div id="divMain">
</div>
<input id="btn" type="button" value="Clear&Add"/>

这是 jQuery 代码

var a = $('<a/>').attr({'id':'aH','href':'#'}).text('Hello');
a.click(function(){
    alert('hello');
});
$('#divMain').append(a);



$('#btn').click(function(){
   var newA = $('#aH');
    $('#divMain').html('');
    $('#divMain').append(newA);
});

这里是 jsfiddle

只需单击 fiddle 中的警报链接,它就会显示警报。现在单击 Clear&Add 按钮。现在单击警报。它不起作用。

最佳答案

您需要事件委托(delegate)来将事件与动态添加的元素绑定(bind)。您还需要创建 ID 为 aH 的元素,因为您已经从 DOM 中删除了元素而不保留它。

Live Demo

$(document).on('click', '#aH', function(){
    alert('hello');
});

您可以尝试添加全局创建的a,您将不需要再次绑定(bind)click。

$('#divMain').append(a);

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery api

关于javascript - 清除并附加 html 后单击不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20866142/

相关文章:

javascript - 使用 Javascript、jQuery 和 underscore.js 从多维数组中删除重复项

javascript - SAPUI5中的动画

jquery - 按类检查文档是否匹配元素

javascript - Laravel - 显示更多/更少按钮冲突

javascript - 根据设备的大小激活图像 slider

javascript - 将 Sinon 与 Typescript 和接口(interface)结合使用

javascript - Google Maps Api 显示灰色 map

javascript - 使用 css 或 js 以一定倾斜 Angular 或椭圆形状旋转对象 360 度

jquery - 重新加载页面后应用CSS

html - 如何将 ionic 侧菜单嵌套到 ionic 导航 View 中?