简体   繁体   English

如何在 jQuery 中检查空对象

[英]How to check null objects in jQuery

I'm using jQuery and I want to check the existence of an element in my page.我正在使用 jQuery,我想检查页面中是否存在某个元素。 I have written following code, but it's not working:我已经编写了以下代码,但它不起作用:

if($("#btext" + i) != null) {
    //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}

How do I check the existence of the element?如何检查元素的存在?

Check the jQuery FAQ ...检查jQuery 常见问题...

You can use the length property of the jQuery collection returned by your selector:您可以使用选择器返回的 jQuery 集合的 length 属性:

if ( $('#myDiv').length ){}

(Since I don't seem to have enough reputation to vote down the answer...) (因为我似乎没有足够的声誉来否决答案......)

Wolf wrote:写道:

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!在 undefined 或 null 对象上调用 length 属性将导致 IE 和 webkit 浏览器失败!

Instead try this:而是试试这个:

 // NOTE!! THE FOLLOWING IS WRONG; DO NOT USE! -- EleotleCram if($("#something") !== null){ // do something }

or或者

 // NOTE!! THE FOLLOWING IS WRONG; DO NOT USE! -- EleotleCram if($("#something") === null){ // don't do something }

While it is true that calling the length property on an undefined or null object will cause browsers to fail, the result of jQuery's selectors (the $('...')) will never be null or undefined.虽然在 undefined 或 null 对象上调用 length 属性确实会导致浏览器失败,但 jQuery 的选择器($('...'))的结果永远不会为 null 或 undefined。 Thus the code suggestions make no sense.因此,代码建议毫无意义。 Use one of the other answers, they make more sense.使用其他答案之一,它们更有意义。


(Update 2012) Because people look at code and this answer is pretty high up the list: For the last couple of years, I have been using this small plugin: (2012 年更新)因为人们看代码,这个答案在列表中名列前茅:在过去的几年里,我一直在使用这个小插件:

  jQuery.fn['any'] = function() {
     return (this.length > 0);
  };

I think $('div').any() reads better than $('div').length , plus you won't suffer as much from typos: $('div').ayn() will give a runtime error, $('div').lenght will silently most likely always be falsy.我认为$('div').any()$('div').length读起来更好,而且你不会因为拼写错误而受苦: $('div').ayn()会出现运行时错误, $('div').lenght很可能总是假的。

__ __
Edits november 2012: 2012 年 11 月的编辑:

1) Because people tend to look at code and not read what is said around the code, I added two big caveat lector notes to the quoted code of Wolf. 1)因为人们倾向于看代码而不是阅读代码周围所说的内容,所以我在 Wolf 引用的代码中添加了两个大警告讲师注释。
2) I added code of the small plugin I use for this situation. 2)我添加了我用于这种情况的小插件的代码。

The lookup function returns an array of matching elements.查找函数返回匹配元素的数组。 You could check if the length is zero.您可以检查长度是否为零。 Note the change to only look up the elements once and reuse the results as needed.请注意更改为仅查找元素一次并根据需要重用结果。

var elem = $("#btext" + i);
if (elem.length != 0) {
   elem.text("Branch " + i);
}

Also, have you tried just using the text function -- if no element exists, it will do nothing.另外,您是否尝试过只使用 text 函数——如果不存在元素,它什么都不做。

$("#btext" + i).text("Branch " + i);

jquery $() function always return non null value - mean elements matched you selector cretaria. jquery $() 函数总是返回非空值 - 意味着与您的选择器 cretaria 匹配的元素。 If the element was not found it will return an empty array.如果未找到该元素,它将返回一个空数组。 So your code will look something like this -所以你的代码看起来像这样 -

if ($("#btext" + i).length){
        //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}

no matter what you selection is the function $() always returns a jQuery object so that cant be used to test.无论您选择什么,函数$()始终返回一个 jQuery 对象,因此无法用于测试。 The best way yet (if not the only) is to use the size() function or the native length property as explained above.最好的方法(如果不是唯一的)是使用size()函数或如上所述的本机长度属性。

if ( $('selector').size() ) {...}                   

使用“未定义”怎么样?

if (value != undefined){ // do stuff } 

In jQuery 1.4 you get the $.isEmptyObject function, but if you are forced to use an older version of jQ like us poor Drupal developers just steal use this code:在 jQuery 1.4 中你得到了 $.isEmptyObject 函数,但是如果你被迫使用像我们可怜的 Drupal 开发人员这样的旧版本的 jQ,只需窃取使用以下代码:

// This is a function similar to the jQuery 1.4 $.isEmptyObject.
function isObjectEmpty(obj) {
  for ( var name in obj ) {
    return false;
  }
  return true;
}

Use it like:像这样使用它:

console.log(isObjectEmpty(the_object)); // Returns true or false.
if ( $('#whatever')[0] ) {...}

The jQuery object which is returned by all native jQuery methods is NOT an array, it is an object with many properties;所有原生 jQuery 方法返回的 jQuery 对象不是一个数组,它是一个具有许多属性的对象; one of them being a "length" property.其中之一是“长度”属性。 You can also check for size() or get(0) or get() - 'get(0)' works the same as accessing the first element, ie $(elem)[0]您还可以检查 size() 或 get(0) 或 get() - 'get(0)' 与访问第一个元素的工作方式相同,即 $(elem)[0]

Using the length property you can do this.使用 length 属性可以做到这一点。

jQuery.fn.exists = function(){return ($(this).length < 0);}
if ($(selector).exists()) { 
   //do somthing
}

use $("#selector").get(0) to check with null like that.使用$("#selector").get(0)像这样检查 null 。 get returns the dom element, until then you re dealing with an array, where you need to check the length property. get 返回 dom 元素,直到那时您正在处理一个数组,您需要在其中检查 length 属性。 I personally don't like length check for null handling, it confuses me for some reason :)我个人不喜欢空处理的长度检查,它出于某种原因让我感到困惑:)

when the object is empty return this error:当对象为空时返回此错误:

Uncaught TypeError: Cannot read property '0' of null

I try this code :我试试这个代码:

try{
  if ($("#btext" + i).length) {};               
}catch(err){
  if ($("#btext" + i).length) {
     //working this code if the item, not NULL 
   }
}
if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!在 undefined 或 null 对象上调用 length 属性将导致 IE 和 webkit 浏览器失败!

Instead try this:而是试试这个:

if($("#something") !== null){
  // do something
}

or或者

if($("#something") === null){
  // don't do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM