想象一个函数,其签名如下所示:
function readElement(element: HTMLElement): string;
要实现该功能,您必须检查元素是使用value属性 (ie HTMLInputElement) 还是使用textContent属性 (ie SpanElement) 并获取相应的属性。我要问的是几种可以实现readElement、万无一失且具有高浏览器兼容性的方法。
以下是我过去用来解决问题的方法列表:
- element.value !== undefined
- element.constructor.hasOwnProperty("value")
- typeof element.value === "string"
- [HTMLInputElement, HTMLTextAreaElement,...].some(proto => element instanceof proto)