如何检查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
}
其他回答
我只是喜欢使用普通的javascript来实现这一点。
function isExists(selector){
return document.querySelectorAll(selector).length>0;
}
不需要jQuery(基本解决方案)
if(document.querySelector('.a-class')) {
// do something
}
下面的选项性能更高(注意a类前面没有点)。
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector在jQuery中使用了一个适当的匹配引擎,比如$()(sizzle),并使用了更多的计算能力,但在99%的情况下都会很好。第二个选项更加明确,并且告诉代码要做什么https://jsbench.me/65l2up3t8i
默认情况下-否。
长度属性通常以以下方式用于相同的结果:
if ($(selector).length)
在这里,“选择器”将被您感兴趣的实际选择器替换,无论它是否存在。如果它确实存在,那么length属性将输出一个大于0的整数,因此If语句将变为true,从而执行If块。如果没有,它将输出整数“0”,因此If块不会被执行。
使用jQuery,使用以下语法检查元素是否确实存在。
let oElement = $(".myElementClass");
if(oElement[0]) {
// Do some jQuery operation here using oElement
}
else {
// Unable to fetch the object
}
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
这是对杰夫·阿特伍德主持的《放牧守则》播客的回应