克隆并更改div的ID后,jQuery无法通过该ID访问元素

Kno*_*tle 3 jquery

克隆(div)容器并更改ID后,似乎无法使用ID选择器来访问它,这是在做错什么吗?我知道克隆是正确的,我知道id改变的很好,但是我不能再使用默认的Jquery选择器来获取该元素。

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
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 5

您尚未将克隆插入DOM。这会$("#abc")在当前文档中查找该ID,但该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
Run Code Online (Sandbox Code Playgroud)