1

I am trying to have it so that I can create elements with the same class name in HTML, and jQuery will count them, based on order. I have successfully done it before with regular JavaScript, however, I am trying to learn the jQuery API right now. Is there a way I can do it like this? As of now, it is not accepting the $(...)[#] method.

for (var i = 0; i < $('.description').length; i++) {
    $('.description')[i].before($('<div/>', {
        id: 'q' + (i+1),
        class: 'qNumber',
        text: (i+1) + ')',
    }));
}
4

1 回答 1

3
$('.description').before(function(i) {
    return $('<div/>', {
        id      : 'q' + (i+1),
        'class' : 'qNumber',
        text    : (i+1) + ')',
    });
});

小提琴

于 2013-10-04T00:25:26.273 回答