如何在 Safari 中使 DOM 处理程序可枚举?
我需要枚举我之前修改过的 DOM 元素的所有属性。我可以用 Firefox、Chrome 和 Opera 做到这一点,但用 Safari 就不行(我暂时不关心 IE)。
<a id="link">Link...</a>
<script>
var link = document.getElementById("link");
var foo = function (baz) {};
link.onclick = foo;
alert ("onclick" in link); // true
alert (link.hasOwnProperty("onclick")); // true
alert (link.propertyIsEnumerable("onclick"));
// false with Chrome, Safari, Opera*
</script>
*:虽然该属性在 Opera 中不可枚举,但无论如何都可以枚举!
for (p in link)
if (p==="onclick")
alert (p); // onclick
我可以通过在分配之前删除 onclick
属性,在 Chrome 中使第三个 alert
输出 true
:
delete link.onclick;
但该属性尚未在 Safari 中枚举。
我什至尝试使用 EcmaScript 5 对象方法 defineProperty:
Object.defineProperty (link, onclick, {
value: foo,
enumerable: true,
configurable: true,
writable: true
});
但它返回错误:
类型错误:DOM 对象不支持 DefineProperty
有什么建议吗?
PS 为什么 Safari 的行为与 Chrome 不同,尽管它们都基于 Webkit?
I need to enumerate all the properties of my DOM elements which I previously modified. I could do it with Firefox, Chrome and Opera but I could not with Safari (I don't care about IE for the moment).
<a id="link">Link...</a>
<script>
var link = document.getElementById("link");
var foo = function (baz) {};
link.onclick = foo;
alert ("onclick" in link); // true
alert (link.hasOwnProperty("onclick")); // true
alert (link.propertyIsEnumerable("onclick"));
// false with Chrome, Safari, Opera*
</script>
*: Although the property is not enumerable in Opera it is anyway enumerated!!!
for (p in link)
if (p==="onclick")
alert (p); // onclick
I can make the third alert
output true
in Chrome by deleting the onclick
property before assigning it:
delete link.onclick;
But the property is not yet enumerated in Safari.
I even tried with the EcmaScript 5 Object method defineProperty:
Object.defineProperty (link, onclick, {
value: foo,
enumerable: true,
configurable: true,
writable: true
});
but it returns the error:
TypeError: defineProperty is not supported on DOM Objects
Any suggestions?
P.S. Why does Safari behave different from Chrome although they are both based on Webkit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将 useragent 与在 Webkit JavaScriptCore。 Chrome 的 Webkit 版本与 Safari 不同,因此标准支持也会相应有所不同。
Compare the useragent to the Webkit version in which the EcmaScript5 Object methods were implemented in Webkit JavaScriptCore. The Webkit version of Chrome is different from that of Safari, so standards support will vary accordingly.