简体   繁体   English

DOM 元素添加到 DOM 树后是否立即可用?

[英]Is a DOM element available immediately after it has been added to the DOM tree?

After dynamically appending a chunk of HTML to a document (Example uses jQuery, but question is valid for all JavaScript), can I assume that the appended elements are available immediately afterwards?在将一段 HTML 动态附加到文档后(示例使用 jQuery,但问题对所有 JavaScript 都有效),我是否可以假设附加元素之后立即可用?

$('#content').append('<p>Content</p><button id="newbutton">New</button><p>Some more content</p>');
var forExample = $('#newbutton').width(); // Element available?

In my particular case, creating single elements is not practicable.在我的特殊情况下,创建单个元素是不切实际的。 Also, this is long past the document.ready event.此外,这早已超过the document.ready事件。

Yes, they're available immediately.是的,它们立即可用。 jQuery will return you the correct objects, for example, and you may bind elements onto them.例如,jQuery 将返回正确的对象,您可以将元素绑定到它们上。

But as they're not rendered while your script is running, size computations aren't always immediately made, so if you need the dimensions of the objects you might have to do但是由于它们在您的脚本运行时不会被渲染,因此尺寸计算并不总是立即进行,因此如果您需要对象的尺寸,您可能必须这样做

setTimeout(function(){
    var forExample = $('#newbutton').width();
    // use size
}, 0); // 0 is enough to tell the engine to render before it executes the callback

Note that the behavior of browser is different if you're incrementally debugging (the script isn't really "running").请注意,如果您进行增量调试(脚本并未真正“运行”),则浏览器的行为会有所不同。

Yes, it's directly available.是的,可以直接使用。 You could have tested it in 1min on fiddle... http://jsfiddle.net/adxbH/你可以在 1 分钟内在小提琴上测试它...... http://jsfiddle.net/adxbH/

var newButton = document.createElement('button');

newButton.id = 'newbutton';
newButton.innerHTML = 'button_test';
document.body.appendChild(newButton);
var forExample = document.getElementById('newbutton');
alert(forExample.offsetWidth);​

As you can see, also very easy without using jQuery.如您所见,不使用 jQuery 也很容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM