我在条件语句中使用 .length
方法来轮询页面是否存在外部加载的对象(在它存在之前我无法使用 jQuery 设置它的样式):
function hackyFunction() { if($('#someObject').length<1) { setTimeout(hackyFunction,50) } else { $('#someObject').someMethod() }}
length
是最好的方法吗?
最佳答案
如果您只是在寻找一个特定的元素,您可以使用 document.getElementById
function hackyFunction() {
if (document.getElementById("someObject")) {
// Exist
} else {
// Doesn't exist
}
}
关于javascript - 如何检查元素是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3900526/