开发者

JQuery going through a set of UL and dynamically set ids incremently on each one

开发者 https://www.devze.com 2022-12-30 22:25 出处:网络
I have an unordered list which contains several items called \'oListItems\' the UL has a class but no id.

I have an unordered list which contains several items called 'oListItems' the UL has a class but no id.

The class OuteroListItems contains many of oListitems

 oList.AppendFormat("<ul class='OuteroListItems'>");
            oList.AppendFormat("<li>");
            oList.AppendFormat("<ul class='oListItems'>");
            oList.AppendFormat("<li>" + s.sName + "</li>");
            oList.AppendFormat("<li>" + s.eName + "</li>");
            oList.AppendFormat("<li>" + s.SDate + "</li>");
            oList.AppendFormat("<li>" + s.EDate + "</li>");
            oList.AppendFormat("</ul>");
            oList.AppendFormat("</li>");
            oL开发者_运维问答ist.AppendFormat("</ul>");

I want for each .oListItem class that gets retrieved, add dynamically an id to it.

 var o = $(".oListItem");

    $.each(o, function (){

      var f = $(this).attr("id", 'listItem' + i);

        i++;
    });

wasent sure on the approach, this is what I have so far?


You can do this use .each() (off the element collection), note that ID cannot start with a number:

$('.oListItems').each(function(i) {
  $(this).attr('id', 'listItem' + i);
});

The .each() function gets 2 parameters, (index, element), you just need the first, in this case i is the index (zero-based) of the current .oListItem you're on.


What you have looks fine to me except that you want to declare and initialize i somewhere. But it can be simpler. You can use the index jQuery passes into the $.each callback, and just assign directly to the id property on the given element rather than constructing a jQuery object around it just so you can set the attribute via attr. E.g.:

$.each(o, function(index) {

    this.id = 'listItem' + index;

});

But if you want to construct the jQuery object around each element for other reasons, :

$.each(o, function(index) {

    $(this).attr("id", 'listItem' + index);

});

(Also no need to declare and use that variable f if you don't use it, so I left it out of the above.)

0

精彩评论

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