如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 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相同的性能,并且被认为有点简洁。测试条件的性能和逻辑运算符的使用。
附带说明:对象函数需要重写>.<'但我所做的这个测试是为了研究简洁而富有表现力的条件反射。
资源:逻辑与(带短路评估)
其他回答
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
这是对杰夫·阿特伍德主持的《放牧守则》播客的回应
您可以使用此选项:
// if element exists
if($('selector').length){ /* do something */ }
// if element does not exist
if(!$('selector').length){ /* do something */ }
$.contains()是您想要的吗?
jQuery.incontains(容器,已包含)如果第二个参数提供的DOM元素是第一个参数提供DOM元素的后代,则$.contains()方法返回true,无论它是直接子元素还是更深层的嵌套。否则,返回false。仅支持元素节点;如果第二个参数是文本或注释节点,$.contains()将返回false。注意:第一个参数必须是DOM元素,而不是jQuery对象或纯JavaScript对象。
尝试测试DOM元素
if (!!$(selector)[0]) // do stuff
试试这个。
简单、简短,可在整个项目中使用:
jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin
用法:
console.log($("element-selector").exists());
_________________________________
或更短:(当您不想定义jQuery插件时):
if(!!$("elem-selector")[0]) ...;
甚至
if($("elem-selector")[0]) ...;