Javascript DOM按用户类型识别节点? [英] Javascript DOM identifying nodes by user type?
问题描述
如果我有一个tr儿童节点的tbody,我该怎么给每个tr一个用户指定的值来识别它?
If I have a tbody with some tr children nodes, how can I give each tr a user specified value that can be used to identify it?
例如我想做一些类似的事情:
For example I want to do something like:
mytr1 = mytbody.createElement('tr');
mytr2 = mytbody.createElement('tr');
mytr1.userident = 'firstname';
mytr2.userident = 'lastname';
tbody.appendChild(mytr1);
tbody.appendChild(mytr2);
然后有一个孩子能够访问其兄弟姐妹,如:
Then have the ability for one child to access its sibling like:
mystr1.parentNode.getByUserident('lastname')
我不想使用id,因为对象被动态创建和销毁,并且名称对tr元素无效。
I don't want to use id's because the objects are dynamically created and destroyed, and names are not valid for tr elements.
推荐答案
您可以使用数据集。
这是HTML5,但它是相当受支持的。 数据集支持
以下是如何使用它们:
You could use datasets.
It's HTML5, but it's fairly supported. Datasets support
Here's how to use them :
mytr1 = mytbody.createElement('tr');
mytr2 = mytbody.createElement('tr');
mytr1.dataset.userident = 'firstname';
mytr2.dataset.userident = 'lastname';
tbody.appendChild(mytr1);
tbody.appendChild(mytr2);
要访问它们,
意味着您正在使用事件绑定和处理: br>
For accessing them,
implying you're using event binding and handling :
var userident = evt.target.dataset.userident;
编辑
其实现在所有浏览器都支持。
唯一部分支持的部分是访问 .dataset 属性。
只需在元素上使用 .getAttribute('data-userident')和 .setAttribute('data-userident','firstname')。
Actually it's supported by all browsers right now.
The only partially supported part is the access to the .dataset property.
Simply use .getAttribute('data-userident') and .setAttribute('data-userident','firstname') on your elements.
这篇关于Javascript DOM按用户类型识别节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!