Javascript 获取选定的元素类型

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

Get selected element type

javascriptjquery

提问by Silver Light

I want to get the type of element, that I've got selected using jQuery selectors.

我想获取使用 jQuery 选择器选择的元素类型。

Markup:

标记:

<select name="a"></select>
<input name="b" type="text" />
<textarea name="c"></textarea>

Javascript:

Javascript:

var field_names = new Array(
    'a',
    'b',
    'c'
);

for(var i = 0; i < field_names.length; i++) {
    var field = $('[name=' + required_fields[i] + ']:visible');

    // ?????
    // What do I write here to get one of those outputs:
    //    Element with name a is <select>
    //    Element with name b is <input>
    //    Element with name c is <textarea>

    alert('Element with name ' + required_fields[i] + ' is ' + element_type);
}

回答by Jacob Relkin

Simple:

简单的:

var element_type = '<' + field.get(0).tagName.toLowerCase() + '>';

In a nutshell, this retrieves the DOM element associated with fieldand gets its tag name via the tagNameattribute inherited from DOMElement, then transforms the result to lowercase using String's toLowerCase()method. Some browsers will return the tagNamein uppercase, so for consistency you should transform it to lower case.

简而言之,这field通过从tagName继承的属性检索与关联的 DOM 元素并获取其标记名称DOMElement,然后使用StringtoLowerCase()方法将结果转换为小写。某些浏览器会tagName以大写形式返回,因此为了保持一致性,您应该将其转换为小写。

回答by lonesomeday

Use the DOM element's tagNameproperty:

使用 DOM 元素的tagName属性:

var element_type = field[0].tagName;

Note that browsers are not entirely consistent about the case returned by tagName, so you should probably call toLowerCaseto be safe: field[0].tagName.toLowerCase().

请注意,浏览器对于 返回的大小写并不完全一致tagName,因此您可能应该调用toLowerCase以确保安全:field[0].tagName.toLowerCase()