2013-04-23 193 views
4

編輯:jQuery的克隆元素被改變了可變

工作示例現在jsbin.com/ivukar/10


這裏是我想要做的,歸納爲核心的步驟沒有所有的細節那對你來說是沒有意義的:

  1. 從DOM克隆現有的div並將該克隆存儲在變量中
  2. 從DOM
  3. 刪除該分區追加克隆DIV到DOM
  4. 進行更改到div中的DOM
  5. HTML內容刪除div和插入克隆再次

現在執行以下步驟,讓我們說我們的div的HTML內容爲「測試」,我希望以下內容:

  1. 變量已經存儲有內容的div「測試」
  2. 事業部從DOM
  3. 股利去除附加到DOM與內容「測試」
  4. 事業部的頁面改變有內容「改變」
  5. 事業部刪除的網頁上。 DIV追加到身體再次與內容「測試」,因爲存儲在一個變量,應該不會被改變的DOM

受到影響,但會發生什麼,一旦是爲我作出這樣的改變元素的html內容使用例如:$('#element').html('altered');它也改變了變量的內容......

我看不出爲什麼會這樣做,因爲只有在將變量追加到DOM時才引用該變量,我沒有改變變量的內容......

這是一個JsBin鏈接,所以你可以看到我的意思。

或可替代這裏是示例代碼:

<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
<script> 
var saved = ''; 

function my_clone() 
{ 
saved = $('#el').clone(); 
$('#output').append("<a href='#' onclick='my_remove();'>Remove version on screen</a> ----- This removes any element with the id 'el'<br>"); 
} 

function my_remove() 
{ 

$('#el').remove(); 
$('#output').append("<a href='#' onclick='my_append();'>Append clone to body</a> ----- This takes the cloned object stored in the variable 'saved' and appends it to the html body<br>"); 

} 

function my_append() 
{ 

$('body').append(saved); 
$('#output').append("<a href='#' onclick='my_alter();'>Alter .html() of element</a>----- This alters the html of any element with the id 'el'<br>"); 

} 

function my_alter() 
{ 

$('#el').html('altered'); 
$('#output').append("<a href='#' onclick='my_remove_again();'>Remove version on screen again</a>----- This removes any element with the id 'el'<br>"); 

} 

function my_remove_again() 
{ 
$('#el').remove(); 
$('#output').append("<a href='#' onclick='my_append_again();'>Append clone to body</a> ----- This again takes the object stored in the 'saved' variable, which is separate from the DOM and should not have been affected by the html change and appends to the html body<br>"); 
} 

function my_append_again() 
{ 
$('body').append(saved); 
} 


</script> 
<style> 
#el {color:red;} 
</style> 
</head> 
<body> 

<div id="el"> 
    <div id="various">Various</div> 
    <div id="sub">Sub 
     <div id="and-sub-sub">And Sub-Sub</div> 
    </div> 
    <div id="elements">Elements</div> 
</div> 

<br><br> 
<div id="output"> 
<a href="#" onclick="my_clone();">Clone</a> ------ This stores the clone into a global variable called 'saved'<br> 
</div> 

</body> 
</html> 

誰能告訴我在哪裏,我錯了嗎?

謝謝。

回答

2

的問題是,你被分配實際的DOM元素saved而非HTML內容。

的老把戲:

saved = $("#el").clone().wrap('<div/>').parent().html(); 

你先換克隆在父div其HTML返回。

更新JSBIN http://jsbin.com/ivukar/4

參考:Get DOM element as string

+0

感謝。在我的實時系統中,正在被克隆的元素中有輸入,而只是克隆.html()會丟失輸入中的任何東西。例如。 [http://jsbin.com/ivukar/5/]你知道一種獲取輸入數據的方法嗎?乾杯。 – CMR 2013-04-23 15:06:19

+0

我有完全相同的問題。我通過在刪除內容之前將輸入值保存在局部變量中,然後在所有內容之後用'$(「input#abc」).val(a);''替換空的輸入值來解決它,其中'a'是存儲值從以前。 – 2013-04-23 15:25:45

+0

謝謝,我會試試 – CMR 2013-04-23 15:38:42

-1
saved = $('#el').clone(); 

應該

saved = $('#el').clone().html();