javascript Jquery检查输入是否具有特定名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18980866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery to check if an input has a specific name?
提问by Kamran Ahmed
Is there any function to check if an input has a specific name in jquery, like we check the existense of a class using hasClass()
?
是否有任何函数可以检查输入在 jquery 中是否具有特定名称,就像我们使用hasClass()
?
For example if I have an input
例如,如果我有一个输入
<input type="checkbox" class="col_control" checked="checked" name="sr_column" data-columnno="0" />
<input type="checkbox" class="col_control" checked="checked" name="sr_column" data-columnno="0" />
so that I can check hasName("sr_column")
and it returns true
这样我就可以检查hasName("sr_column")
并返回true
回答by ThiefMaster
el.name == 'text'
No need for any jQuery! If you do have a jQuery object, use jq_el[0].name == 'text'
instead.
不需要任何 jQuery!如果您确实有 jQuery 对象,请jq_el[0].name == 'text'
改用。
Of course you can also use jQuery to access this, using either jq_el.prop('name')
or jq_el.attr('name')
(it's available both as a property and an attribute).
当然,您也可以使用 jQuery 来访问它,使用jq_el.prop('name')
或jq_el.attr('name')
(它可以作为属性和属性使用)。
If you want jq_el.hasName(...)
, you can define the function like this:
如果需要jq_el.hasName(...)
,您可以像这样定义函数:
$.fn.hasName = function(name) {
return this.name == name;
};
回答by Amit
Try this also
也试试这个
var name = $("#id").attr("name");
OR
或者
var name = $("#id").prop("name");
if(name=="sr_column")
{
//your code
}
回答by nietonfir
Just for completeness, one can also use $.filter()
on the jQuery objects and check the length of the list, e.g.
只是为了完整性,还可以$.filter()
在 jQuery 对象上使用并检查列表的长度,例如
var $inputs = $("input");
if ($inputs.filter("[name=text]").length > 0) {
// do something here
}