我正在尝试将 div 内容从一个地方复制到另一个地方,为此我使用类似的东西:
$('#newDiv').html($('#oldDiv').html());
问题是某些子元素使用 jquery 的 bind() 方法附加了事件。我还想将这些事件复制到新位置。
您知道如何执行此“事件副本”吗?
最佳答案
描述
您在复制内容时就创建了动态内容。
您需要 jQuery .live()
或 delegate()
方法将事件绑定(bind)到动态创建的 html。
根据您使用的 jQuery 版本选择 .live()
或 delegate()
。
.live() Available since jQuery 1.3. Attach an event handler for all elements which match the current selector, now and in the future.
.delegate() Available since jQuery 1.4.2. Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
查看我的样本和这个 jsFiddle Demonstration
示例
<div id="newDiv"></div>
<div id="oldDiv"><a>click me</a></div>
$("a").live("click",function() {
alert("click");
});
// copy content
$('#newDiv').html($('#oldDiv').html());
更多信息
关于javascript - 将事件从子元素复制到不同的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10247356/