如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
对于jQuery,您不需要>0,这就是您所需要的:
if ($(selector).length)
使用vanilla JS,您可以使用:
if(document.querySelector(selector))
如果要将其转换为返回bool的函数:
const exists = selector => !!document.querySelector(selector);
if(exists(selector)){
// some code
}
其他回答
您可以在java脚本中使用长度检查元素是否存在。如果长度大于零,则元素存在;如果长度为零,则元素不存在
// These by Id
if ($("#elementid").length > 0) {
// Element is Present
} else {
// Element is not Present
}
// These by Class
if ($(".elementClass").length > 0) {
// Element is Present
} else {
// Element is not Present
}
如果您使用
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
你会暗示链接是可能的,而不是可能的。
这样会更好:
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
或者,从常见问题解答:
if ( $('#myDiv').length ) { /* Do something */ }
您也可以使用以下选项。如果jQuery对象数组中没有值,那么获取数组中的第一个项将返回undefined。
if ( $('#myDiv')[0] ) { /* Do something */ }
有一种奇怪的现象叫做短路调节。没有多少人知道这个功能,所以请允许我解释一下<3.
//you can check if it isnt defined or if its falsy by using OR
console.log( $(selector) || 'this value doesnt exist' )
//or run the selector if its true, and ONLY true
console.log( $(selector) && 'this selector is defined, now lemme do somethin!' )
//sometimes I do the following, and see how similar it is to SWITCH
console.log(
({ //return something only if its in the method name
'string':'THIS is a string',
'function':'THIS is a function',
'number':'THIS is a number',
'boolean':'THIS is a boolean'
})[typeof $(selector)]||
//skips to this value if object above is undefined
'typeof THIS is not defined in your search')
最后一位允许我查看我的类型有什么样的输入,并在列表中运行。如果列表中有一个值,我使用OR(||)运算符跳过并使其无效。这具有与Switch Case相同的性能,并且被认为有点简洁。测试条件的性能和逻辑运算符的使用。
附带说明:对象函数需要重写>.<'但我所做的这个测试是为了研究简洁而富有表现力的条件反射。
资源:逻辑与(带短路评估)
您可以使用:
if ($(selector).is('*')) {
// Do something
}
也许更优雅一点。
我发现if($(selector).length){}不够。当选择器为空对象{}时,它将自动中断应用程序。
var $target = $({});
console.log($target, $target.length);
// Console output:
// -------------------------------------
// [▼ Object ] 1
// ► __proto__: Object
我唯一的建议是对{}执行额外的检查。
if ($.isEmptyObject(selector) || !$(selector).length) {
throw new Error('Unable to work with the given selector.');
}
我仍然在寻找一个更好的解决方案,尽管这个有点重。
编辑:警告!当选择器是字符串时,这在IE中不起作用。
$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE