用唯一ID动态替换相同的div ID

时间:2019-12-27 16:48:45

标签: javascript jquery dom

我想知道是否有简单的JS / JQuery将容器内的div ID从'one'更改为唯一ID(例如'one_1', 'one_2', 'one_3'

<div id="container">
  <div id="one">ONE</div>
  <div id="one">ONE</div>
  <div id="one">ONE</div>
</div>

所需的输出

<div id="container">
  <div id="one_1">ONE</div>
  <div id="one_2">ONE</div>
  <div id="one_3">ONE</div>
</div>

到目前为止,我已经提取了三个div,但是现在需要替换文本:

document.getElementById("container").querySelectorAll("#one")

4 个答案:

答案 0 :(得分:2)

您可以遍历容器的子代并更新其ID:

var children = document.getElementById('container').children;
for (var i = 0; i < children.length; i++) {
  var child = children[i];
  child.id = child.id + "_" + (i + 1);
}

答案 1 :(得分:1)

jQuery解决方案:

$("#container div").each(function( index ) {
 this.id = this.id+"_"+(index+1);
});

单行(感谢Andreas的评论)

$("#container div").attr("id", (index, oldId) => oldId + "_" + (index + 1))

答案 2 :(得分:1)

您可以使用以函数为第二个参数的.attr()版本:

jQuery(($) => {
  $('#container > div').attr('id', (index, id) => `${id}_${index + 1}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="one">ONE</div>
  <div id="one">ONE</div>
  <div id="one">ONE</div>
</div>

或者,如果您不能使用ES6 + Javascript:

jQuery(function ($) {
  $('#container > div').attr('id', function (index, id) {
    return id + '_' + (index + 1);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="one">ONE</div>
  <div id="one">ONE</div>
  <div id="one">ONE</div>
</div>

答案 3 :(得分:0)

$(".changer").on("click",function(){
var i = 1;
$("#container").children().each(function(){
	var id = this.id;
	$(this).attr("id",(id + "_" + i));
	i++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="one">ONE</div>
  <div id="one">ONE</div>
  <div id="one">ONE</div>
</div>
<button class="changer">
Change IDs
</button>