简体   繁体   中英

jQuery how to reference an id that is an index

I am trying to generate markup via jQuery with a loop which creates n many div s, each being assigned an id of the loop index. When I want to call a particular div by its id how do I concatonate the # with i ? Thanks?

        for(int i=0; i<ListSize; i++) {
            $('<div></div>').attr('id', i).appendTo('#loadMe');

            // Help, how to reference an id that is an index?
            $('<h1></h1>').html(firstName).appendTo('#'+i);    // This doesn't work.
            $('<h1></h1>').html(lastName).appendTo('#'+i);     // This doesn't work.

        }

Build the markup in the loop, change the DOM once :

var container = $([]);

$.each(ListSize, function(i) {
    var div  = $('<div />', {id : 'div' + i}),
        h1_1 = $('<h1 />', {text: firstName}),
        h1_2 = $('<h1 />', {text: lastName});

    container = container.add( div.append(h1_1, h1_2) );
});

$('#loadMe').append( container );

FIDDLE

instead of this you can do this like:

for(int i=0; i<ListSize; i++) {
    //this would create the DOM element with the index as its id
    var iDiv = $('<div id=' + i + '></div>');

    $('<h1>' + firstName + '</h1>').appendTo(iDiv);
    $('<h1>' + lastName + '</h1>').appendTo(iDiv);

    //I usually prefer create the all DOM elements I want then append it to 
    iDiv.appendTo('#loadMe');
}

And you can also create the whole DOM elements in one line code:

for(int i=0; i<ListSize; i++) {
    var iDiv = $('<div id=' + i + '><h1>' + firstName + '</h1><h1>' + lastName + '</h1></div>').appendTo('#loadMe');
}

but if you insist on using the IDs you can do what you want like:

for(int i=0; i<ListSize; i++) {
    $('<div></div>').attr('id', i).appendTo('#loadMe');

    $('<h1></h1>').html(firstName).appendTo($('#loadMe').find('#'+i));
    $('<h1></h1>').html(lastName).appendTo($('#loadMe').find('#'+i));

}

Your code works for me, but change int to var .

for(var i=0; i<ListSize; i++) {
    var iDiv = $('<div id=' + i + '></div>');
    iDiv.appendTo('#loadMe');

    $('<h1>' + firstName + '</h1>').appendTo(iDiv);
    $('<h1>' + lastName + '</h1>').appendTo(iDiv);

}

Here is the live demo. http://jsfiddle.net/Ez7ZH/1/

I would strongly suggest prefixing your IDs with at least one letter. Aside from being a semantic improvement, IDs beginning with numbers are only valid as of HTML5 (see here for further details).

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