如何使用jQuery检查ID是否存在?

[英]How check for ID existence using jQuery?


I want to have a line of code similar to below:

我想要一行代码如下所示:

var name = $('#input-name').attr("value");

However, the id 'input-name' is not guaranteed to exist. How do I check for its existence so that the assignment does not throw an error?

然而,id 'input-name'并不保证存在。如何检查它的存在性,使赋值不会抛出错误?

4 个解决方案

#1


54  

if ($('#input-name').length) {
  // do something
}

#2


3  

Check for .length or .size() on the object. The select won't fail, jQuery will always return an object.

检查对象上的.length或.size()。选择不会失败,jQuery将始终返回一个对象。

#3


1  

In my test the assignment didn't cause an error, it simply returned undefined.

在我的测试中,赋值没有导致错误,只是返回了未定义的值。

In which case the solution would be the following:

在这种情况下,解决办法如下:

var name = $('#input-name').attr("value");
if (name) {
  // blah blah
}

Or maybe:

或者:

var name = $('#input-name').attr("value") || 'defaultValue';

... if that makes sense in your case.

…如果这对你的情况有意义的话。

#4


0  

var name;
if ($('#input-name').length > 0)   
name= $('#input-name').attr("value");

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/08/09/c2156f0f28cc2d52e6b9fcb0c48dd918.html



 
  © 2014-2022 ITdaan.com 联系我们: