pei*_*rix 265 jquery jquery-selectors
检测jQuery-selector是否返回空对象的最佳方法是什么.如果你这样做:
alert($('#notAnElement'));
Run Code Online (Sandbox Code Playgroud)
你得到[object Object],所以我现在这样做的方式是:
alert($('#notAnElement').get(0));
Run Code Online (Sandbox Code Playgroud)
这将编写"未定义",因此您可以检查它.但看起来非常糟糕.还有什么其他方式?
Mag*_*nar 486
我最喜欢的是使用这个极小的便利来扩展jQuery:
$.fn.exists = function () {
return this.length !== 0;
}
Run Code Online (Sandbox Code Playgroud)
使用如下:
$("#notAnElement").exists();
Run Code Online (Sandbox Code Playgroud)
比使用长度更明确.
duc*_*lip 193
if ( $("#anid").length ) {
alert("element(s) found")
}
else {
alert("nothing found")
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*lio 66
选择器返回一个jQuery对象数组.如果未找到匹配的元素,则返回空数组.您可以检查.length选择器返回的集合,或检查第一个数组元素是否为"未定义".
您可以在IF语句中使用以下任何示例,它们都会产生相同的结果.如果选择器找到匹配元素,则为true,否则为false.
$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
Run Code Online (Sandbox Code Playgroud)
小智 39
我喜欢做这样的事情:
$.fn.exists = function(){
return this.length > 0 ? this : false;
}
Run Code Online (Sandbox Code Playgroud)
那么你可以这样做:
var firstExistingElement =
$('#iDontExist').exists() || //<-returns false;
$('#iExist').exists() || //<-gets assigned to the variable
$('#iExistAsWell').exists(); //<-never runs
firstExistingElement.doSomething(); //<-executes on #iExist
Run Code Online (Sandbox Code Playgroud)
我喜欢使用presence,灵感来自Ruby on Rails:
$.fn.presence = function () {
return this.length !== 0 && this;
}
Run Code Online (Sandbox Code Playgroud)
你的例子变成:
alert($('#notAnElement').presence() || "No object found");
Run Code Online (Sandbox Code Playgroud)
我发现它优于提议的$.fn.exists因为你仍然可以使用布尔运算符if,但是真实的结果更有用.另一个例子:
$ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
$ul.append('...')
Run Code Online (Sandbox Code Playgroud)
我的偏好,我不知道为什么这还没有在jQuery中:
$.fn.orElse = function(elseFunction) {
if (!this.length) {
elseFunction();
}
};
Run Code Online (Sandbox Code Playgroud)
像这样使用:
$('#notAnElement').each(function () {
alert("Wrong, it is an element")
}).orElse(function() {
alert("Yup, it's not an element")
});
Run Code Online (Sandbox Code Playgroud)
或者,在CoffeeScript中看起来:
$('#notAnElement').each ->
alert "Wrong, it is an element"; return
.orElse ->
alert "Yup, it's not an element"
Run Code Online (Sandbox Code Playgroud)
这是在JQuery文档中:
http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/
alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193285 次 |
| 最近记录: |