i have created a script to associate data to dom nodes, something like the jQuery.data method. Basically the script sets a property on the node that is the key of an object that will contain the data of every node, but in IE 7 setting a property on a text node throws an error:
var a=document.createElement("div");
a.test="test开发者_JAVA技巧";
alert(a.test); //Works and shows "test"
var a=document.createTextNode("text");
a.test="test"; //Throws an error
So do you know a workaround for this bug? Or maybe is there a property that is almost useless on text nodes that allows me to set data on it?
Best plan: don't do this.
In general, it's a bad idea to assign properties to a host object (i.e. anything provided by the browser rather than native JavaScript objects). Host objects are not obliged to allow this kind of extension (a.k.a. "expandos") and many (for example, ActiveX objects in IE) do not. Furthermore, IE allows you to prevent expandos on all DOM nodes within a document by using document.expando = false;
.
One alternative would be to use jshashtable (disclaimer: I wrote it) to store data for text nodes. It's a hash table implementation that allows you to use any object (not just strings) as a key.
I believe that this is because createTextNode
makes straight text as opposed to an element. Therefore, you cannot assign properties to it.
I would try doing createElement("p")
(or any element type) if you want to show text.
EDIT: This is incorrect. See Tim Down's answer for the solution.
精彩评论