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

时间:2021-03-27 09:22:14

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");

#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");