【发布时间】:2019-11-04 15:47:20
【问题描述】:
我想检查输入元素是复选框还是文本类型。
我知道我能做到:
//Type of input..
if ( input.type === "checkbox" )
//Contains the property..
if ( "checked" in input )
但我的问题是:为什么hasOwnProperty 返回 false?
我只想使用:
input.hasOwnProperty("checked")
但它每次都返回 false。
input 不是一个对象吗?
我不这么认为,但typeof 说是:
typeof input // returns "object"
那是怎么回事?!
代码示例:
const input = document.querySelector("input")
if ( input instanceof HTMLInputElement ) {
console.dir(input);
console.info(typeof input);
console.log("with 'hasOwnProperty'",input.hasOwnProperty("checked"));
console.log("with 'in'","checked" in input);
console.log("with 'type'",input.type === "checkbox");
}
<input type="checkbox" />
The documentation about HTMLInputElement,只有类型复选框才有checked属性:
【问题讨论】:
-
checked本身不是input的成员;它是HTMLInputElement原型的一部分。 -
更具体地说,它是反映控件当前状态的
getter,而不是HTMLInputElement特定实例的属性。 -
相关讨论:stackoverflow.com/questions/20381239/…(完全披露:我自己的回答)