javascript 将javascript变量添加到html div标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17793346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:38:57  来源:igfitidea点击:

Adding javascript variable to html div tag

phpjavascript

提问by user2605321

I want to know if it's possible to add a javascript variable to html div tag just like php For example:

我想知道是否可以像 php 一样向 html div 标签添加 javascript 变量例如:

    $id = 1;
    <div id="test'.$id.'"></div>

<script>
var id = '1';
</script>
<div id="test..???.??"></div>

回答by Paul Roub

Not as simply as that, no. You cando something like:

不是那么简单,不。您可以执行以下操作:

<script>
  var id = '1';
</script>

and then later:

然后:

<script>
  document.writeln('<div id="' + id + '">');
</script>

...

</div>

回答by zzlalani

You can try this

你可以试试这个

<div id="id_change"></div>    
<script>
var id = 1;
var set_id = document.getElementById("id_change").id + id;
document.getElementById("id_change").id = set_id;
</script>

Hope this answers your question

希望这能回答你的问题

EDIT

编辑

Put the <script>code after the divelse it wont find the div

<script>代码放在divelse之后,它不会找到div

回答by Christian Bekker

You could use Jquery's .attr() method? Take a look here: http://api.jquery.com/attr/

您可以使用 Jquery 的 .attr() 方法吗?看看这里:http: //api.jquery.com/attr/

http://jsfiddle.net/PxUqU/2/

http://jsfiddle.net/PxUqU/2/

var currrentID = $("div").attr("id");
var someInt = 1;
$("div").attr("id", currrentID+someInt);

回答by OpenSorceress

var divs = document.getElementsByTagName("div"),
    newId = 1;

divs[0].setAttribute("id", newId);