Вопрос

change this:

<ul>
    <li>list one</li>
    <li>list two</li>
    <li>list three</li>
</ul>
<ul>
    <li>list one</li>
    <li>list two</li>
    <li>list three</li>
</ul>

to this:

<ul id="list_project01_01">
    <li id="itm_project01_01">list one</li>
    <li id="itm_project01_02">list two</li>
    <li id="itm_project01_03">list three</li>
</ul>
<ul id="list_project01_02">
    <li id="itm_project01_04">list one</li>
    <li id="itm_project01_05">list two</li>
    <li id="itm_project01_06">list three</li>
</ul> 

The tricky part is the incrementing number. Any suggestions?

Это было полезно?

Решение

I have no idea why you want to do this but you can use the following bit of jQuery to achieve this.

   var toBeId = "list_project01_";
   var ulCtr = 0; 

   $("ul").each(function(){
        if(ulCtr < 10){
            $(this).prop("id", toBeId + "0" + ulCtr);
        }
        else{
            $(this).prop("id", toBeId + ulCtr);
        }
        ulCtr++;
    });

    $("ul").each(function(){
        var liCtr = 0;
        $(this).children("li").each(function(){
            var parentId = $(this).parent().prop("id");
            if(liCtr < 10){
                $(this).prop("id", parentId + "_0" + liCtr);
            }
            else{
                $(this).prop("id", parentId + "_" + liCtr);
            }
            liCtr++;
        });
    });

Here's a working FIDDLE

Другие советы

this simple piece of Javascript should do the job for you.

window.onload=function(){
var uls = document.getElementsByTagName("ul");
var cumul = 1;

for (var i = 0; i < uls.length; ++i) {
    if (i < 10) {
        uls[i].id = "list_project01_0" + (i + 1);
    }
    else {
        uls[i].id = "list_project01_" + (i + 1);
    }

    var lis = uls[i].getElementsByTagName("li");
    for (var j = 0; j < lis.length; ++j) {
        if (cumul < 10) {
            lis[j].id = "itm_project01_0" + cumul;
        }
        else {
            lis[j].id = "itm_project01_" + cumul;
        }

        ++cumul;
    }
}
};

Of course, this will work only if you don't have any other list in your document.

Loop through them with javascript.

for(var i=0;i<elems.length;i++){
    /*
      do stuff with i (index)
      or do stuff with elems[i] (element at index i)
    */
}

Here is a fiddle

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top