想象一下其签名如下的函数:
function readElement(element: HTMLElement): string;
要实现该功能,您必须检查元素是否使用value
属性(即HTMLInputElement
)或textContent
属性(即SpanElement
)并获取相应的属性。我要问的是有几种方法可以实现readElement
,是万无一失的,并且具有很高的浏览器兼容性。
以下是我过去用来解决问题的方法列表:
element.value !== undefined
element.constructor.hasOwnProperty("value")
typeof element.value === "string"
[HTMLInputElement, HTMLTextAreaElement,...].some(proto => element instanceof proto)
要测试对象是否具有属性,只需使用'prop' in obj
:
[...document.body.querySelectorAll('*')].forEach((el)=> {
console.log(el.tagName + ' contains: ' + readEl(el));
})
function readEl(el) {
return 'value' in el ? el.value : el.textContent || false;
}
<p>para</p>
<input value="input" />
<textarea>textarea</textarea>
<div>div</div>