使用 Javascript 和 JQuery 获取控件的类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13493251/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:57:11  来源:igfitidea点击:

Getting the type of a control using Javascript and JQuery

javascriptjquerycontrols

提问by Abishek

I am trying to use JQuery to get the type of control and following is the code that I am using.

我正在尝试使用 JQuery 来获取控件类型,以下是我正在使用的代码。

$('#selCity').attr('type')

where selCity is of type select. When I try the above code it returns as undefined but when I use the alternative code with Javascript, it returns the correct type.

其中 selCity 是选择类型。当我尝试上面的代码时,它返回为 undefined 但当我使用带有 Javascript 的替代代码时,它返回正确的类型。

Please look into this fiddle to understand it clearly: http://jsfiddle.net/Ye8e9/

请查看这个小提琴以清楚地理解它:http: //jsfiddle.net/Ye8e9/

Could someone advice on how I can acheive this correctly using JQuery? Is this an issue with JQuery or am I making a mistake?

有人可以就我如何使用 JQuery 正确实现这一点提出建议吗?这是 JQuery 的问题还是我犯了错误?

回答by Sibu

Use

利用

$('#selCity').prop('type')

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

从 jQuery 1.6 开始,.attr() 方法为尚未设置的属性返回 undefined。此外,.attr() 不应用于普通对象、数组、窗口或文档。要检索和更改 DOM 属性,请使用 .prop() 方法。

Reference

参考

DEMO

演示

回答by Raab

if you mean the type of tag, the use this

如果你的意思是标签的类型,使用这个

 $("#selCity").get(0).tagName

See your demo here

在此处查看您的演示

回答by A. Wolff

Use nodeName to get 'type of Tag'. '.type' refers to attribute 'type' which select doesn't have.

使用 nodeName 获取“标签类型”。'.type' 指的是 select 没有的属性 'type'。

document.getElementById('selCity').nodeName

回答by rajesh kakawat

you are getting undefined because there is not type attribute in select.

您未定义,因为选择中没有类型属性。

try this one

试试这个

$('#selCity')[0].tagName;