[英]javascript - use html ID tag or add property to element?
I am using Prototype.js, but this probably applies to jQuery as well: I have a html list with a bunch of rows where each row is related to an object in javascript which is contained in an array. 我正在使用Prototype.js,但这可能也适用于jQuery:我有一个包含一堆行的html列表,其中每一行都与数组中包含的javascript对象相关。 So: 所以:
<ul>
<li id="0">blah</li>
<li id="1">blahblah></li>
</ul>
I am currently using the id tag to find the javascript object refers to. 我目前正在使用id标记来查找所引用的javascript对象。 So when the user clickes on the row, the event code will look something like: 因此,当用户单击该行时,事件代码将类似于:
var clickedItem = event.findElement('li');
if (clickedItem) {
var itemID = clickedItem.identify();
var foundBlah = blahList[itemID];
Is using the ID tags a bad idea and should I instead be adding a property to each row when it is created, such as: 使用ID标签不是一个好主意,我应该在创建时在每行中添加一个属性,例如:
var blah = new Blah('blah');
$(list).insert(<li>blah</li>).blah = blah;
and then just retrieving that value in the event handler? 然后只是在事件处理程序中检索该值?
I'm unfamiliar with Prototype, but in jQuery, this sounds like a job for .data()
, which allows you to attach arbitrary data to an element: 我不熟悉Prototype,但是在jQuery中,这听起来像.data()
,它允许您将任意数据附加到元素:
$(list).insert($("<li>blah</li>").data("blah", blah));
// later...
var blah = $(event.target).data("blah");
Update 更新资料
Prototype has methods Element#store
and Element#retrieve
which similarly allow you to attach metadata: 原型具有Element#store
和Element#retrieve
,它们类似地允许您附加元数据:
$(list).insert(new Element("li").insert("blah").store("blah", blah));
// later...
var blah = event.findElement("li").retrieve("blah")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.