为元素赋值
我想知道是否可以为元素对象赋值。在本例中,我希望将 setTimeout() 函数的返回值分配给元素对象中的对象。
例如:
var elem = document.getElementById('target');
elem.timeouts = new Object();
elem.timeouts.sometimeout = setTimeout('...', 1000);
所以我可以这样做:
clearTimeout(elem.timeouts.sometimeout);
我知道这可能看起来很糟糕,但是否有可能或会导致浏览器着火并打开用户等。
谢谢。
I was wondering if it was possible to assign values to an element object. In this case, I wish to assign the returns from the setTimeout()
function to an object within an element object.
For example:
var elem = document.getElementById('target');
elem.timeouts = new Object();
elem.timeouts.sometimeout = setTimeout('...', 1000);
So I could then do:
clearTimeout(elem.timeouts.sometimeout);
I know this might seem bad practice etc, but is it possible or will it cause browsers to catch fire and turn on their user etc.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
DOM 元素是宿主对象(又名非本机),因此它们几乎可以做任何想做的事情。不保证您的 Expando 能够正常工作。特别是 IE 曾经遇到过问题。强烈建议阅读这篇文章:
扩展 DOM 有什么问题< /a> 作者:@kangax
(来自一位经历过这种坏习惯的缺点的 Prototype.js 开发人员。他们重写了整个库,只是为了让自己免于更多的麻烦)
现在,如果您添加
uniqueID
到非 IE 浏览器中的元素(IE 默认情况下有它),然后您的data
函数就变成了一个简单的查找 ~ O(1)。真实信息将存储在闭包中。它比
jQuery.data
快 2-4 倍 (test)1.) 哈希表
2.) 数组
如果你想避免同时扩展,你可以使用数组来保存elements (但速度较慢)
Array.prototype.indexOf (后备)
不客气! :)
DOM elements are Host objects (aka non-native) and as such they can do almost anything they want. It's not guaranteed that your expandos will work. In particular IE used to have problems with them. It's highly recommended to read this article:
What’s wrong with extending the DOM by @kangax
(it is from one of the Prototype.js developers who experienced the drawbacks of such bad habits. They've rewritten the whole library just to save themselfs from more headaches)
Now if you add
uniqueID
to elements in non-IE browsers (IE has it by default) and then yourdata
function becomes a simple lookup ~ O(1). The real information will be stored in a closure.It's 2-4x faster than
jQuery.data
(test)1.) Hash table
2.) Array
If you want to avoid expandos all together you can use an array to hold elements (but it's slower)
Array.prototype.indexOf (fallback)
You're welcome! :)
JS 检索的 DOM 元素有可能是 JS 变量:) ..顺便说一句,以这种方式做这些事情并不常见。我认为 @galambalazs 的答案更加深入和完整;)
It's possible, DOM elements retrieved by JS, are JS variables :) ..BTW it's not a common practice do that stuff in that way. I think the answer of @galambalazs is more deep and complete ;)
如果你使用jquery,你可以在“数据”中讲述它
http://api.jquery.com/jQuery.data/
if you are using jquery, you can story it in the "data"
http://api.jquery.com/jQuery.data/
不,实际上这应该很好用。据我了解,将返回添加到对象应该没问题。在我看来,这比将其存储在全局容器中要好。
No, actually that should work just fine. From what I understand, adding that return to the object should be fine. It's better than storing it in a global container IMO.