我正在使用.length
方法在一个条件语句中来轮询页面是否存在外部加载的对象(在它存在之前,我无法用jQuery来进行样式设置):
function hackyFunction() {
if($('#someObject').length<1)
{ setTimeout(hackyFunction,50) }
else
{ $('#someObject').someMethod() }}
使用length
是做这件事情的最佳方式吗?
我正在使用.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
}
}
是的,你应该使用 .length
。不能使用 if ($('#someObject')) ...
,因为 jQuery 选择器 返回一个 jQuery 对象,在 JavaScript 中任何对象都是真值。
如果您正在查找ID,则只应该有一个,因此您也可以编写:
if($('#someObject')[0])
是的,.length
是可接受的,通常我也会使用它。
使用jQuery,检查长度很容易。
if (!$('#someObject').length) {
console.log('someObject not present');
}
document.getElementById
(如果按ID获取元素)进行检查。if (document.getElementById('someObject')) {
console.log('someObject exists');
}