简体   繁体   中英

How do you append to a div name that is being dynamically created in a for loop with jquery?

I'm trying to do something like this:

        var size = skillsArray.length;
        for (i = 0; i < size; i++) {
            var divString = "'#Skill" + i +"'";
            $(divString).append(skillsArray[i]);
        }

To start out my prototype, skillsArray had 5 values. So my javascript was this:

        $('#Skill0').append(skillsArray[0]);
        $('#Skill1').append(skillsArray[1]);
        $('#Skill2').append(skillsArray[2]);
        $('#Skill3').append(skillsArray[3]);
        $('#Skill4').append(skillsArray[4]);

My html was this:

        <div id='Skill0'></div>
        <div id='Skill1'></div>
        <div id='Skill2'></div>
        <div id='Skill3'></div>
        <div id='Skill4'></div>

And everything worked fine.

Now that I want to work with larger dynamically sized arrays, I want to use loops.

So my first step was to write the html div tags out in a javascript loop, which worked:

 for (i=0; i<size; i++)
 {
   html += "<div id='Skill" + i + "'></div>";
 }

Before I tried step 2 which is what my question is about, it did show the first 5 skills just fine, and every skill after was just blank. (To be expected since I hadn't updated my javascript yet to do the append to each div, it still only did the first 5.)

So, I was ready to try step 2 and use a for loop for the appends. How can I do this? The code I pasted in at the very top did not fill each div with anything at all.

Thanks in advance for the help! -Holly

Try removing the single quotes in this line : var divString = "'#Skill" + i +"'"; like this:

var divString = "#Skill" + i;

摆脱选择器字符串中的单引号:

var divString = "#Skill" + i;

You could try this

$("div[id^='Skill']").each(function(i) {
    $(this).append(skillsArray[i]);
});

Do everything in the same loop:

var size = skillsArray.length;
for (i = 0; i < size; i++) {
    // create a div
    var $elem = $("<div id='Skill" + i + "'></div>");

    // append the skills to div
    $elem.append(skillsArray[i]);

    // append the div to body (or wherever)
    $('body').append($elem);
}

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