JQuery:将行为转移到克隆对象
我试图通过将 clone() 方法绑定到 doubleclick 事件来快速制作类的副本。到目前为止,我的代码是:
<style type="text/css">
.draggable { float:left; clear: both; }
</style>
<script type="text/javascript">
$(function() {
copyit = function() {
$(this).clone().appendTo("body").css('position','absolute').draggable();
}
$('.draggable').dblclick(copyit);
$('.draggable').draggable();
});
</script>
<div class="draggable">Hi There!</div>
<div class="draggable">What's up?</div>
一切正常,除了克隆元素添加到 DOM 后我无法让它们克隆自身。非常感谢任何帮助。
I'm trying to quickly make copies of a class by binding the clone() method to the doubleclick event. My code, so far is:
<style type="text/css">
.draggable { float:left; clear: both; }
</style>
<script type="text/javascript">
$(function() {
copyit = function() {
$(this).clone().appendTo("body").css('position','absolute').draggable();
}
$('.draggable').dblclick(copyit);
$('.draggable').draggable();
});
</script>
<div class="draggable">Hi There!</div>
<div class="draggable">What's up?</div>
Everything works, except I can't get the cloned elements to clone themselves once they are added to the DOM. Any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的猜测是您没有将 dblclick 事件绑定到新的 DOM 节点。在这种情况下,您实际上有两种方法可以实现此目的:
您可以使 dblclick 成为实时(或委托)事件,如下所示:
$('.draggable').live('dblclick', copyit);
看:
http://api.jquery.com/直播/
http://api.jquery.com/delegate/
您可以使克隆复制对象的事件通过传递 true 来实现,如下所示:
$(this).clone(true).appendTo("body").css('position','absolute').draggable();
看:
http://api.jquery.com/clone/
My guess is that you are not binding the dblclick event to the new DOM nodes. In this case you actually have 2 ways you can accomplish this:
You can make the dblclick a live (or delegate) event like this:
$('.draggable').live('dblclick', copyit);
see:
http://api.jquery.com/live/
http://api.jquery.com/delegate/
You can make the clone copy the events of the object by passing it true, like this:
$(this).clone(true).appendTo("body").css('position','absolute').draggable();
see:
http://api.jquery.com/clone/
使用
.live()
设置双击处理程序:Set up the double-click handler with
.live()
: