// 片段 1:為 .xxbgcons > div 動態分配 ID
$('.xxbgcons>div').each(function(i) {
$(this).attr('id', "tab1_div_" + i);
});
// 片段 2:操作固定 ID #myidg 下的 a 標簽
$("#myidg a").eq(0).html("333");
$("#myidg a").eq(1).html("444");
兩段代碼針對不同元素,片段 1 生成的 ID (tab1_div_0...) 未在片段 2 中使用。
// 若需對動態生成的每個 div 內部 a 標簽操作
$('.xxbgcons>div').each(function(i) {
$(this).attr('id', "tab1_div_" + i);
// 直接在這裡操作當前 div 內的 a
$(this).find('a').eq(0).html("內容" + i);
});
// 或收集 ID 後統一處理
var ids = [];
$('.xxbgcons>div').each(function(i) {
var id = "tab1_div_" + i;
$(this).attr('id', id);
ids.push(id);
});
ids.forEach(function(id) {
$("#" + id + " a").eq(0).html("統一處理");
});
#myidg) 與動態 ID 混淆。