问题
Say I have the following JavaScript in a HTML page
<html>
<script>
var i=0;
function data()
{
i++;
var id="form"+i;
}
</script>
<body>
<a href="#x" onclick="data();"</a>
</body>
</html>
How do I get the value of the variable id as the id if the tag.please anyone help me
回答1:
Try this:
<html>
<script>
var i=0;
function data(ele)
{
i++;
ele.setAttribute("id","form"+i);
}
</script>
<body>
<a href="#x" onclick="data(this);"</a>
</body>
</html>
回答2:
You wanted to add id to element. Try this fiddle its using JQuery.
Though i really don't understand the reason you wanted to assign ID dynamically. If you wanted to read the elements that's why? then i would suggest there are better ways to read elements instead of generating dynamic id's. Check getElements by tag and class name.
<div class="IMDIV">
Here is element
</div>
$(function(){
$(".IMDIV").attr("id", "testId")
});
来源:https://stackoverflow.com/questions/20282509/how-can-set-javascript-variable-value-as-id-attribute-of-a-html-element