[英]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. 我试图通过带有循环的jQuery生成标记,该循环创建n个div
,每个div
被分配一个循环索引的id
。 When I want to call a particular div
by its id
how do I concatonate the #
with i
? 当我想通过其id
调用特定的div
,如何用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 : 在循环中构建标记,一次更改DOM:
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 );
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: 您还可以在一行代码中创建整个DOM元素:
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: 但是如果您坚持使用ID,则可以执行以下操作:
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
. 您的代码对我有用,但是将int
更改为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/ http://jsfiddle.net/Ez7ZH/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.