在ID类中添加增量值

时间:2018-08-27 13:10:22

标签: javascript while-loop

我是javascript的新朋友。如何在span HTML内部HTML文件中添加ID值。

我的HTML是:

<!DOCTYPE html>
<html>
<body>
<div>Special characters are:<br/>
<span class="We2" datas2="display">Sample Datas are...</span><br/>
<div><span datas2="display">How do I increment the id or class when I dynamically add the content...</span></div>

<div><span datas2="display">when the code actually runs, 10 will get spit out to</span></div>

<span datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>

<span datas2class="We2" datas2="display">$$

动态添加内容时如何增加ID或类...

<span datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>
        </div>
</body>

</html>

我希望输出是:

<!DOCTYPE html>
<html>
<body>
<div>Special characters are:<br/>
<span id="value1" class="We2" datas2="display">Sample Datas are...</span><br/>
<div><span id="value2" datas2="display">How do I increment the id or class when I dynamically add the content...</span></div>

<div><span id="value3" datas2="display">when the code actually runs, 10 will get spit out to</span></div>

<span id="value4" datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>

<span id="value5" datas2class="We2" datas2="display">$$

动态添加内容时如何增加ID或类...

<span id="value6" datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>
        </div>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您需要执行以下步骤:

  1. 您需要获取所有具有属性datas2 = "display"的元素,可以使用querySelectorAll('[datas2 = "display"]')
  2. 您需要声明一个全局变量j,该变量将更改与id串联的value值的计数,例如value+i

var elem = document.querySelectorAll('[datas2 = "display"]');
var j = 1;
for(var i=0; i< elem.length; i++){
  //set id value
  elem[i].id = 'value'+j;
  j++;
}
<div>Special characters are:<br/>
<span class="We2" datas2="display">Sample Datas are...</span><br/>
<div><span datas2="display">How do I increment the id or class when I dynamically add the content...</span></div>

<div><span datas2="display">when the code actually runs, 10 will get spit out to</span></div>

<span datas2class="We2" datas2="display">How do I increment the id or class when I dynamically add the content...</span>

<span datas2class="We2" datas2="display">$$

您将需要对以下代码段中的inspect element元素使用浏览器<span>,以检查id是否正确存在。

相关问题