如何检测选择器是否返回null? [英] How can I detect if a selector returns null?

查看:94
本文介绍了如何检测选择器是否返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检测jQuery选择器是否返回空对象的最佳方法是什么. 如果您这样做:

What is the best way to detect if a jQuery-selector returns an empty object. If you do:

alert($('#notAnElement'));

您获得了[object Object],所以我现在的方法是:

you get [object Object], so the way I do it now is:

alert($('#notAnElement').get(0));

,它将写为"undefined",因此您可以对此进行检查.但这似乎很糟糕.还有什么其他方法?

which will write "undefined", and so you can do a check for that. But it seems very bad. What other way is there?

推荐答案

我的最爱是使用这种小巧的方便性来扩展jQuery:

My favourite is to extend jQuery with this tiny convenience:

$.fn.exists = function () {
    return this.length !== 0;
}

使用方式:

$("#notAnElement").exists();

比使用长度更明确.

这篇关于如何检测选择器是否返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆