我试图得到:
document.createElement('div') //=> true
{tagName: 'foobar something'} //=> false
在我自己的脚本中,我曾经只使用它,因为我从来不需要tagName
作为财产:
if (!object.tagName) throw ...;
因此,对于第二个对象,我想出了以下作为快速解决方案 - 这基本上是有效的。 ;)
问题是,它取决于浏览器强制执行只读属性,但并非所有浏览器都这样做。
function isDOM(obj) {
var tag = obj.tagName;
try {
obj.tagName = ''; // Read-only for DOM, should throw exception
obj.tagName = tag; // Restore for normal objects
return false;
} catch (e) {
return true;
}
}
有好的替代品吗?
这可能会令人感兴趣:
function isElement(obj) {
try {
//Using W3 DOM2 (works for FF, Opera and Chrome)
return obj instanceof HTMLElement;
}
catch(e){
//Browsers not supporting W3 DOM2 don't have HTMLElement and
//an exception is thrown and we end up here. Testing some
//properties that all elements have (works on IE7)
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object");
}
}
它是的一部分DOM,二级 http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html.
Update 2:这就是我在自己的库中实现它的方式:
(前面的代码在 Chrome 中不起作用,因为 Node 和 HTMLElement 是函数而不是预期的对象。此代码在 FF3、IE7、Chrome 1 和 Opera 9 中进行了测试)。
//Returns true if it is a DOM node
function isNode(o){
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
}
//Returns true if it is a DOM element
function isElement(o){
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)