【发布时间】:2011-09-20 15:49:05
【问题描述】:
我知道我们可以使用 (javascript)
if (typeof textbox === "object") { }
但是有没有方法可以让我确保对象是一个文本框?
【问题讨论】:
-
textbox是什么意思?textarea,input...?
标签: javascript dom object textbox
我知道我们可以使用 (javascript)
if (typeof textbox === "object") { }
但是有没有方法可以让我确保对象是一个文本框?
【问题讨论】:
textbox 是什么意思? textarea, input...?
标签: javascript dom object textbox
var isInputText = obj instanceof HTMLInputElement && obj.type == 'text';
【讨论】:
window.HTMLInputElement === otherWindow.HTMLInputElement 将是错误的,因此 instanceof 运算符也可能意外返回 false。也适用于 iframe 和弹出窗口。在这些情况下,检查tagName 可以工作,正如已经提到的其他答案。
if(textbox instanceof HTMLInputElement && textbox.getAttribute("type") == "text") {
alert("I'm an input text element");
}
【讨论】:
从 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;
}
【讨论】:
'tel' ?
element.isContentEditable
element.isContentEditable 对于可编辑的输入可能是假的,所以不要相信这是真的。 readonly 属性也可能是相关的。
如果您要查找的是文本输入:
if (textbox.tagName == "input" && textbox.getAttribute("type") == "text") {
// it's a text input
}
如果您正在寻找文本区域
if (textbox.tagName == "textarea") {
// it's a textarea
}
【讨论】:
你在寻找这样的东西吗?
if(textbox.tagName && textbox.tagName.toLowerCase() == "textarea") {
alert('this is a textarea');
}
如果你需要知道它是否是文本输入,你可以这样做:
if(textbox.tagName && textbox.tagName.toLowerCase() == "input" && textbox.type.toLowerCase() == "text") {
alert('this is a text input');
}
【讨论】:
我想你可能想要获取一个元素的引用,然后检查 .type 的返回值,即
var element = document.getElementById('element_in_question');
if(element.type == "textarea"){
console.log('I must be textarea');
}
【讨论】:
evt.target.type 给了我“文本”。