2011-09-22 49 views
2

克隆我的(div)容器並更改id後,我似乎無法使用id選擇器,我在做什麼有問題?我知道克隆是正確的,我知道id改變了,但我不能再使用默認的jquery選擇器來獲取該元素。jquery克隆和更改id的id後,無法通過該id訪問該元素

var clone = $('#test').clone(); 
clone.attr('id', 'abc'); 

alert(clone.attr('id')); // gives 'abc' 
alert($("#abc").html()); // gives null <------------ WHY? 
alert(clone.html());  // gives correct html 

回答

4

您還沒有將克隆插入到DOM中。此$("#abc")在當前文檔中查找該ID,但它尚未出現。

這工作:

var clone = $('#test').clone(); 
clone.attr('id', 'abc'); 

alert(clone.attr('id'));   // gives 'abc' 
$(document.body).append(clone);  // <==== Put the clone into the document 
alert($("#abc").html());   // gives correct html