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'並不保證存在。如何檢查它的存在性,使賦值不會拋出錯誤?
54
if ($('#input-name').length) {
// do something
}
3
Check for .length or .size() on the object. The select won't fail, jQuery will always return an object.
檢查對象上的.length或.size()。選擇不會失敗,jQuery將始終返回一個對象。
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.
…如果這對你的情況有意義的話。
0
var name;
if ($('#input-name').length > 0)
name= $('#input-name').attr("value");
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/08/09/c2156f0f28cc2d52e6b9fcb0c48dd918.html。