简体   繁体   中英

jQuery/JavaScript: Avoid unique ID's for each row in a table?

I'm not sure if I'm doing this the right way. I have table which I fill with rows that each represent a song in a playlist. Right now, I assign a unique ID per row, and also assign som jQuery.data() to each ID.

        html += '\
            <tr id="track-' + i + '" class="tracks-row"> \
                <td class="track"><a id="play-'+ i +'" class="play"></a><a id="play2-' + i + '">' + song.song_track + '<span class="mix-style">' + song_mix + '</span></a></td> \
                <td class="artist">' + song.song_artist + '</td> \
                <td class="favourites-holder"><a id="favourite-' + i + '" class="favourites"></a></td> \
                ' + delete_holder + ' \
            </tr> \
        ';

So as you can see, each row has an ID like track-1, track-2 etc.

Is there another way to populate a playlist like this without assigning unique ID's to each track, or is this how it's supposed to be done? Each track has some properties like this:

        $("#track-" + i).data("song_id", song.song_id);
        $("#track-" + i).data("song_artist", song.song_artist);
        $("#track-" + i).data("song_track", song.song_track);
        $("#track-" + i).data("song_mix", song.song_mix);
        $("#track-" + i).data("ps_id", song.ps_id);

... and also .click events for each track, which allows the user to play, sort, drag etc... It just feels like I'm doing it wrong :)?

You could store a reference to each generated row in your loop (assuming html only contains the HTML for a single row):

var row = $(html).appendTo("#table");
var data = row.data();

data["song_id"] = song.song_id;
data["song_artist"] =  song.song_artist;
data["song_track"] = song.song_track;
data["song_mix"] = song.song_mix;
data["ps_id"] = song.ps_id;

row.click(function(){...});

It is not bad to have an ID for an element. But is definitely faster to make use of a reference if you have one and not use jQuery's selector engine over and over again.

Also if you attach the same click handler to every row, it is probably better to just attach one to the table and delegate it, eg

$('#table').delegate('tr', 'click', function(){...});

Unique id's makes sense or use the Metadata plugin to store all the extra data related to each row. http://plugins.jquery.com/project/metadata

It will store the data like:

<li class='someclass' data="{some:'random', json: 'data'}">...</li>

And you can query this like this:

var data = $('li.someclass').metadata();
if ( data.some && data.some == 'data' )
    alert('It Worked!');

Whether the tr needs a unique id or simply a generic class is going to depend a lot on what you intend to do with either javascript (for targeting the rows) or css (also for targeting the rows). If you need to specifically target one row for styling or script effects, a unique id can be an effective way of doing it. If not, then it may be extra "mark-up" that is unnecessary.

In any case, if you do use id's, do make sure they are unique :-)

May be something like this with jquery:

   var songs = function(songList){
    this.songs = songlist;
    this.init();
    }

    $.extend(songs.prototype, {
      init: function(){
       var self = this;
       var table = $('#myTableID');


       for(var i = 0; i < this.songs.length; i++){
        var song = this.songs[i];
        var songData = $('<tr><td class="track">'+song.track+'</td><td class="artist">'+song.artist + '</td></tr>');
        table.append(songData);
        songData.find('td.track:first')click(function){
         self.SongClick(song.track);
        });
    //add other events here


        }

       }

    },

    SongClick : function(track){
    //add here you click event
    },

    otherEvent : function(track){

//add otherEvent code
}
    });

Like this you can create your javascript object and attach events to the dom elements directly as you parse them. You will not need any id's. This approach will create a js object with its constructor so you can say

var so = new songs(mySongList)

when it initializes it will retrieve a table with an id of myTableID and foreach song in the list, it will attach elements to it, and will attach the events directly to those elements.

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