JQuery选择器找不到通过追加添加的对象



页面加载后很长一段时间(例如一分钟或更长时间),我们可以收到推送消息,这将导致我们添加新内容。之后,当我们使用Jquery散列选择器进行查询时,它永远不会返回新添加的内容。在所有情况下,长度始终为零。我们可以看到内容,但选择器什么也不返回。

var section = '<section id="NewSection">Hello</section>';
$('.container').append(section);
if ($('#NewSection').length == 0)
{
    alert('This should not be zero at this point... Why is it?');
}

为了使JQuery能够在附加内容之后找到附加内容,我们需要做些什么吗?

不必要的时候不可铸造。

您正在使用!转换为布尔值,请参阅以下冷运行:

len = $('#NewSection').length

案例len = 0!len = true

if(1){
    // code excecutes
}

案例len = 1!len = false

if(0){
    // no code executes
}

为了有序工作,你应该重新调整你的状况。

// @updated!
var section = '<section id="NewSection">Hello</section>';
$('.container').append(section);
if ($('#NewSection').length > 0) // meaning one or MORE than one element got selected
{
    alert('I should have found this!');
}

这是一个jsfiddle

最新更新