简体   繁体   English

如何使用 javascript 变量作为 html 的 div id?

[英]How can I use javascript variable as html's div id?

<script>
Var x="....";
<\script>
<div id = x> 
Some content 
<\div>

As u can see in the above code I want to use the variable x as div's id but its not working.正如您在上面的代码中看到的那样,我想使用变量 x 作为 div 的 id,但它不起作用。 Any suggestions plz...任何建议请...

You have to set the element's id in your javascript code.您必须在 javascript 代码中设置元素的id See the code snippet below, the text apppears red because the javascript attaches the id red , stored in your variable x , to the div .请参阅下面的代码片段,文本显示为红色,因为 javascript 将存储在变量x中的 id red附加到div

 var x = 'red'; document.getElementsByTagName('div')[0].id = x;
 #red { color: red; }
 <div>Some content</div>

It is not impossible.这并非不可能。 If you want to add id to elements dynamically, you should wait until document will be loaded.如果你想动态地为元素添加 id,你应该等到文档被加载。 Then run script like:然后像这样运行脚本:

var el = document.querySelector() // with some selector rule
// and set  attribute 'id'
el.id = 'myId';

Perhaps you should tell what you want to do and find another way也许你应该告诉你你想做什么并找到另一种方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM