如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
我发现这是最jQuery的方式,IMHO。扩展默认函数很简单,可以在全局扩展文件中完成。
$.fn.exist=函数(){回来此长度;};console.log($(“#yes”).exist())console.log($(“#no”).exist())<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“yes”>id=是</div>
其他回答
检查元素的存在在jQuery官方网站中有完整的文档记录!
使用选择器:if($(“#myDiv”).length){$(“#myDiv”).show();}注意,并不总是需要测试元素是否存在。下面的代码将显示元素(如果存在),并且不做任何操作(无错误)如果没有:$(“#myDiv”).show();
在JavaScript中,一切都是“truthy”或“falsy”,对于数字0表示假,其他一切都是真。所以你可以写:
if ($(selector).length)
你不需要那>0部分。
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
这是对杰夫·阿特伍德主持的《放牧守则》播客的回应
只需检查选择器的长度,如果它大于0,则返回true,否则返回false。
对于ID:
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
对于类别:
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
对于下拉列表:
if( $('#selector option').size() ) { // use this if you are using dropdown size to check
// it exists
}
$.contains()是您想要的吗?
jQuery.incontains(容器,已包含)如果第二个参数提供的DOM元素是第一个参数提供DOM元素的后代,则$.contains()方法返回true,无论它是直接子元素还是更深层的嵌套。否则,返回false。仅支持元素节点;如果第二个参数是文本或注释节点,$.contains()将返回false。注意:第一个参数必须是DOM元素,而不是jQuery对象或纯JavaScript对象。