检查对象是否是文本框 - javascript

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

check if object is a textbox - javascript

javascriptdomobjecttextbox

提问by simplified.

I understand that we can use (javascript)

我知道我们可以使用 (javascript)

if (typeof textbox === "object") { } 

but are there methods which will allow me to ensure that the object is a textbox?

但是有没有方法可以让我确保对象是一个文本框?

回答by Mick Owen

var isInputText = obj instanceof HTMLInputElement && obj.type == 'text';

回答by Onur Y?ld?r?m

As of 2016, use this:

截至2016 年,使用这个:

function isTextBox(element) {
    var tagName = element.tagName.toLowerCase();
    if (tagName === 'textarea') return true;
    if (tagName !== 'input') return false;
    var type = element.getAttribute('type').toLowerCase(),
        // if any of these input types is not supported by a browser, it will behave as input type text.
        inputTypes = ['text', 'password', 'number', 'email', 'tel', 'url', 'search', 'date', 'datetime', 'datetime-local', 'time', 'month', 'week']
    return inputTypes.indexOf(type) >= 0;
}

回答by Jordan

Are you looking for something like this?

你在寻找这样的东西吗?

if(textbox.tagName && textbox.tagName.toLowerCase() == "textarea") {
    alert('this is a textarea');
}

If you need to know if it's a text input, you can do this:

如果您需要知道它是否是文本输入,您可以这样做:

if(textbox.tagName && textbox.tagName.toLowerCase() == "input" && textbox.type.toLowerCase() == "text") {
    alert('this is a text input');
}

回答by Michael Berkowski

If it's a text input you're looking for:

如果它是您正在寻找的文本输入:

if (textbox.tagName == "input" && textbox.getAttribute("type") == "text") {
   // it's a text input
}

If you're looking for a textarea

如果您正在寻找文本区域

if (textbox.tagName == "textarea") {
  // it's a textarea
}

回答by thescientist

I think perhaps you would want to get a reference to an element, and then check for the return value of .type i.e.

我想也许你想得到一个元素的引用,然后检查 .type 的返回值,即

var element = document.getElementById('element_in_question');
if(element.type == "textarea"){
  console.log('I must be textarea');
}

回答by vrunoa

if(textbox instanceof HTMLInputElement && textbox.getAttribute("type") == "text") {
    alert("I'm an input text element");
}