How can set javascript variable value as id attribute of a html element

佐手、 提交于 2021-02-08 12:15:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!