[英]How to auto generate id for child div in JQuery
How to auto generate id for child div in JQuery. 如何在JQuery中自动为子div生成ID。 Please help me so can i solve problem. 请帮助我,我可以解决问题。
there is html code i want to set ids for these so can i apply operation on these. 有HTML代码我想为这些设置ID,所以我可以对这些应用操作。
<div id="main">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
I want to fit this. 我要适合这个。 when click on + it should be max on complete div and when less it should be again on same possition. 当单击+时,应在完整div上最大,而当单击+时,应再次在同一位置。
If you try to create new div and assign it to it one possible solution may be: 如果尝试创建新的div并将其分配给它,则一种可能的解决方案可能是:
<div id="parent">
</div>
for(var i = 0; i< 10; i++) { // suppose I append 10 divs to parent
$('#parent')
.append('<div id="myid_'+ i +'">child'+ i +'</div>');
}
But if you've already child div
s within parent then 但是,如果您已经在父级中创建了div
子级,则
<div id="parent">
<div>child 1</div>
<div>child 2</div>
<div>child 3</div>
</div>
then one possible approach would be 那么一种可能的方法是
$('#parent div').each(function(i) {
$(this).attr('id', 'myid_' + i);
});
<div id="main">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
$('#main .child').each(function(i) {
$(this).attr('id', 'myid_' + i);
});
Another approach would be 另一种方法是
$('#main .child').attr('id', function(i) {
return 'myid_' + i;
});
无法自动执行此操作,因为live()调用不支持ready事件
This will give the child div's ID like child-1
, child-2
etc... child-n 这将给出孩子div的ID,例如child-1
, child-2
等... child-n
$(function(){
var childDivs=$("#main div");
for(var i=0;i<childDivs.length;i++)
{
$(childDivs[i]).attr("id","child-"+i);
}
});
Example : http://jsfiddle.net/nsQcR/12/ (You can check the view source to see the ID's); 示例: http : //jsfiddle.net/nsQcR/12/ (您可以检查视图源以查看ID);
To follow on to thecodeparadox's response for creating new div and assigning values, if you'd like the id
and other info to be taken from a hash within an array: 如果您希望从数组中的哈希中获取id
和其他信息,请遵循thecodeparadox的响应以创建新的div并分配值。
arry = [{name: name1, addr: addr1, id: id1}, {name: name2, addr: addr2, id: id2}, etc...]
<div id="parent">
</div>
for(var i = 0, l = arry.length; i < l; i++) {
var obj = arry[i]
name = obj.name
pid = obj.pid
addr = obj.addr
$('#parent').append('<div id=' + pid + '>' + name + ': ' + addr + '</div>');
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.