简体   繁体   中英

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:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM