我需要将属性ID设置为位于父<div>中的一组<div>元素。
父<div>有一个ID,一些子<div>有一个ID,而另一些则没有。
HTML代码将是:
<div id="my_parent_div">
<div id="my_child_div_a">Here is some text A</div>
<div>Here is some text B</div>
<div>Here is some text C</div>
<div>Here is some text D</div>
</div>在应用Javascript/JQuery之后,应该如下所示:
<div id="my_parent_div">
<div id="my_child_div_a">Here is some text A</div>
<div id="new_added_id_b">Here is some text B</div>
<div id="new_added_id_c">Here is some text C</div>
<div id="new_added_id_d">Here is some text D</div>
</div>我尝试了以下几点:
<script type="text/javascript">
$('div').each(function(eq, el) {
el = $(el);
if(typeof(el.attr('id')) === "undefined") {
el.attr('id', 'div-' + eq);
}
});
</script>但是它将向所有<div>提供ID,而不需要整个HTML文档中的ID。我只需要将ID设置为没有ID的#my_parent_div的子元素,我希望设置特定的ID(而不是id="div-10", id="div-11", id=div-12)。
我很感激你的建议
发布于 2015-06-10 23:03:47
您的选择器是$('div'),它将针对页面上的所有div元素。若要使其仅在#my_parent_div下选择#my_parent_div,请使用此选择器:$('#my_parent_div div')
代码现在将如下所示:
<script type="text/javascript">
$('#my_parent_div div').each(function(eq, el) {
el = $(el);
if(typeof(el.attr('id')) === "undefined") {
el.attr('id', 'div-' + eq);
}
});
</script>更新:
回答你对评论的问题
如果您想为每个元素有一个特定的id名称,我会说您创建了一个数组,列出了所有的名称。
var ids = ["cat", "dog", "rat", "chicken"];
然后创建一个变量,它每次循环时都会计数,这样您就可以使用它在某个循环上获取数组上的名称。
--所以把它们放在一起,看起来如下:
var count = 0;
$('#my_parent_div div').each(function(eq, el) {
var ids = ["cat", "dog", "rat", "chicken"];
el = $(el);
if(typeof(el.attr('id')) === "undefined") {
el.attr('id', ids[count]);
count++;
}
});发布于 2015-06-10 23:13:35
我建议如下:
// select the relevant element(s),
// set the 'id' property of those elements using prop():
$('#my_parent_div div').prop('id', function (i,v) {
// the first argument ('i') is the index of the current
// element from amongst the collection,
// the second ('v') is the current value of the property
// we're accessing:
// if the current id is an empty string (v === '') or
// it's undefined ('undefined === typeof v)
// we set the id to the string 'new_added_id_' plus
// the String created from the character-code of 97 ('a')
// plus the element's index in the collection. Otherwise,
// if the id is set we return the existing id:
return v === '' || 'undefined' === typeof v ? 'new_added_id_' + String.fromCharCode(97 + i) : v;
});
$('#my_parent_div div').prop('id', function(i, v) {
return v === '' || 'undefined' === typeof v ? 'new_added_id_' + String.fromCharCode(97 + i) : v;
});div {
width: 80%;
margin: 0 auto 0.5em auto;
border: 2px solid #000;
}
div > div[id]::before {
content: 'ID: ' attr(id);
color: #f00;
display: block;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_parent_div">
<div id="my_child_div_a">Here is some text A</div>
<div>Here is some text B</div>
<div>Here is some text C</div>
<div>Here is some text D</div>
</div>
外部JS Fiddle演示,用于实验。
参考文献:
prop()。
https://stackoverflow.com/questions/30768753
复制相似问题