Javascript 给定 id,如何检查元素是下拉列表元素还是文本输入元素?

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

How can I check if an element is a drop down list element or a text input element, given its id?

javascripthtml

提问by omega

In Javascript, given the idof an element (in a Stringformat), how can I check if the idof the element refers to a drop down list element, or a text input element?

在 Javascript 中,给定id元素的of(以某种String格式),如何检查id元素的 是指下拉列表元素还是文本输入元素?

The function should return trueif the idrefers to a drop down list (<select>) element, or a text input element, and falseotherwise.

true如果id指的是下拉列表 ( <select>) 元素或文本输入元素,则该函数应返回,否则应返回false

回答by jfrej

Try using: document.getElementById('idNameGoesHere').tagName

尝试使用: document.getElementById('idNameGoesHere').tagName

So the function could be:

所以函数可以是:

function isSelectOrTextField(idName) {
    var element = document.getElementById(idName);
    if(element.tagName === 'SELECT') {return true;}
    if(element.tagName === 'INPUT' && element.type === 'text') {return true;}
    return false;
}

You could expand this to check for <textarea>as well.

您也可以扩展它以进行检查<textarea>

EDIT :Or choose jbabey's answeras it's using nodeNameand is better formatted.

编辑:或者选择 jbabey 的答案,因为它正在使用nodeName并且格式更好。

apparently nodeNamehas wider browser support.

显然nodeName有更广泛的浏览器支持。

回答by Denys Séguret

If you already have jquery included, you can use the is function:

如果您已经包含 jquery,则可以使用is 函数

$('#myid').is('input, select')

or maybe

或者可能

$('#myid').is('input, textarea, select')

if you want to also include textarea

如果你还想包括 textarea

or

或者

$('#myid').is('input:not([type="button"]), textarea, select')

(this one returns true if it's a textare or a dropdown or an input that is not a button).

(如果它是 textare 或下拉列表或不是按钮的输入,则返回 true )。

You have the whole power of jquery selectorsto adapt your query to your exact needs.

您拥有jquery 选择器的全部功能,可以根据您的确切需求调整您的查询。

Demonstration : http://jsfiddle.net/ELuEJ/(try to change the html)

演示:http: //jsfiddle.net/ELuEJ/(尝试更改html)

回答by jbabey

You can use the nodeNameand typeproperties of the DOM elements to determine this. No external libraries are required.

您可以使用DOM 元素的nodeNametype属性来确定这一点。不需要外部库。

var isSelectOrTextInput = function (element) {
    var nodeName = element.nodeName;

    return nodeName === 'SELECT' || 
        (nodeName === 'INPUT' && 
         element.type.toLowerCase() === 'text');
};

Working sample: http://jsfiddle.net/ytHQD/

工作示例:http: //jsfiddle.net/ytHQD/

回答by Parv Sharma

$('#myId')[0].tagName

you can retrive the dom element and then check the tagName

您可以检索 dom 元素,然后检查 tagName