开发者

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. 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. So when the user clickes on the row, the event code will look something like:

开发者_StackOverflow社区
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:

   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:

$(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:

$(list).insert(new Element("li").insert("blah").store("blah", blah));

// later...
var blah = event.findElement("li").retrieve("blah")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜