Jquery ui奇怪的行为与.clone(true,true)+。remove()

时间:2012-02-28 11:49:19

标签: jquery jquery-ui clone draggable

我遇到了jquery-ui和jquery .clone(),remove()的奇怪行为。 我使用的是jquery 1.7和jquery-ui 1.8.16。 问题是当我使用remove()函数从深度克隆元素中删除元素时,删除会通过从DOM中的元素中删除可拖动属性来影响克隆元素和文档中的相应元素。我不确定我做错了什么,但在我看来,无论是我对克隆(真实,真实)的误解还是jquery-ui中的错误。

考虑以下

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js" type="text/javascript"></script>
  <script type="text/javascript">
  $(document).ready(function() {
    $('#testp').draggable();
    //the following line causes the draggable classes to be removed from the document
    //as well as the cloned object ,the expected behaviour is that that #testp will be 
    //removed only from the clone...
          var test = $("#test")
           .clone(true,true)
           .find('#testp')
           .remove()
           .end(); //some more manipulation here
        });
  </script>
</head>
<body>
  <div id="test">
    <p id="testp">some text</p>
  </div>
</body>
    </html>

更新: 似乎.clone(true,true)仍然保留了一些克隆和原始数据共享的数据。 即使使用类选择器更改ids /应用.draggable()并且不从dom中删除任何元素,拖动克隆也会移动原始而不影响克隆(正如人们所想的那样)。其他处理程序,如点击等,正确克隆

在看到一些关于克隆div(带有(true,true)和draggable插件的问题的帖子后,我决定克制克隆div复制等,只使用detach()并重新附加作为解决方法。

注意其他尝试使用clone(true,true)克隆div并使用draggable()插件的人: 如果克隆(true,true),一些数据将被复制到克隆中,并且通过对其应用draggable(),您将拖动原始数据,我想这不是您想要做的事情。 而是做一个浅的.clone()然后将draggable()绑定到克隆。

2 个答案:

答案 0 :(得分:0)

尝试单独的陈述:

var test = $("#test");
test.clone(true,true).appendTo("whatever").find('#testp').remove();

PS:clone()和remove()在jQuery核心中。 jQuery UI的存在不应该影响它们,但无论如何都要尝试不安装UI。

答案 1 :(得分:0)

请查看:What is the most efficient way to deep clone an object in JavaScript?

请注意,您可能必须取消绑定事件克隆并在克隆过程中重新应用它们 - 具体取决于您的操作方式,如果您在申请时将事件应用于原始事件,则可能需要取消绑定源。您的新申请选项包括原件。

在你的情况下,你正在使用一个id选择器,然后删除它 - 它将删除它找到的id的第一个实例。

您可能需要执行以下操作:(为了清晰起见,详细版本)

var test = $("#test");
var newtest = test.clone(true, true);
newtest.find('#testp').remove();
newtest.attr('id', 'newtest');
newtest.appendTo("#whatever");

也许在这里重新绑定......

请参阅此示例:http://jsfiddle.net/MarkSchultheiss/yfD3r/