在JavaScript或jQuery中动态设置div id [英] Dynamically setting div id in JavaScript or jQuery
本文介绍了在JavaScript或jQuery中动态设置div id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何动态设置div id?这是我的代码:
How to set the div id dynamically? Here is my code:
<div id="q1"></div>
<div id="q2"></div>
<div id="q3"></div>
<div id="q4"></div>
<div id="q5"></div>
现在我想将q4 div id设置为q1,就像在JavaScript中一样。
如何在JavaScript或jQuery中执行此操作?
Now I want to set the q4 div id to q1 something like that in JavaScript. How can I do that in JavaScript or jQuery?
我试过这个。
document.getElementById("q4").id = "q1";
document.getElementById("q2").id = "q5";
但它表示该对象为null或未定义。
but it is saying that the object is null or undefined.
谢谢。
chakri。
Thanks. chakri.
推荐答案
使用jquery:
设置动态一个接一个:
var idCount = 1;
$('div').each(function() {
$(this).attr('id', 'q' + idCount);
idCount++;
});
重新排列你想要的东西:
to rearrange what you want:
$('div#q4').attr('id', 'q1');
$('div#q2').attr('id', 'q5');
这篇关于在JavaScript或jQuery中动态设置div id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文