简体   繁体   English

在html中创建动态ID

[英]Create dynamic id in html

I have my html and javascript code as below.我的 html 和 javascript 代码如下。

<!DOCTYPE html>
<html>
<head>
<style>
        #demo {
            border: 1px solid green;
            padding: 10px;
            margin: 20px;
        }
    </style>
    <style>
        #demo1 {
            border: 1px solid green;
            padding: 10px;
            margin: 20px;
        }
    </style>
<div id ="demo"></div>
<div id ="demo1"></div>
<script>
  var arr_args =  [["ab", "cd"], ["ef", "gh"]];
  var j, x = "";
  for (i=0; i<2; i++) {
    for (j=0; j< 2; j++) {
      x = x + arr_args[i][j] + "<br />"; 
     }
     if(i == 0) {
     document.getElementById("demo").innerHTML = x;
     x="";
     }
     if(i==1) {
        document.getElementById("demo1").innerHTML = x;
    }
  }


</script>
</html>

now instead of me creating demo and demo1 id's.现在而不是我创建演示和演示 1 id。 I need the code t do it dynamically.我需要代码 t 动态执行。 Any help would be appreciated.任何帮助,将不胜感激。

You can use backticks as below to get the id as dynamic您可以使用如下反引号将 id 设为动态

document.getElementById(`demo${i == 0 ? '': i }`).innerHTML = x;

 var arr_args = [ ["ab", "cd"], ["ef", "gh"] ]; var j, x = ""; for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { x = x + arr_args[i][j] + "<br />"; } document.getElementById(`demo${i == 0 ? '': i }`).innerHTML = x; if (i == 0) { x = ""; } }
 #demo1 { border: 1px solid green; padding: 10px; margin: 20px; } #demo { border: 1px solid green; padding: 10px; margin: 20px; }
 <div id="demo"></div> <div id="demo1"></div>

You can use querySelectorAll to select all divs starting with "demo", then use the corresponding index to update.可以使用querySelectorAll选择所有以“demo”开头的div,然后使用对应的索引进行更新。

 var arr_args = [ ["ab", "cd"], ["ef", "gh"] ]; var j, x = ""; //Get all divs with an ID starting with demo var divs = document.querySelectorAll("[id^=demo]"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { x = x + arr_args[i][j] + "<br />"; } //Update the corresponding div divs[i].innerHTML = x; if (i == 0) { x = ""; } }
 #demo1 { border: 1px solid green; padding: 10px; margin: 20px; } #demo { border: 1px solid green; padding: 10px; margin: 20px; }
 <div id="demo"></div> <div id="demo1"></div>

You probably really want to use a CSS class.您可能真的想使用 CSS 类。 .className in JavaScript. JavaScript 中的.className

 //<![CDATA[ /* js/external.js */ var doc, html, bod, nav, mobile, M, I, S, Q, special, unspecial; // for use on other loads addEventListener('load', function(){ doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; mobile = nav.userAgent.match(/Mobi/i) ? true : false; M = function(tag){ return doc.createElement(tag); } I = function(id){ return doc.getElementById(id); } S = function(selector, within){ var w = within || doc; return w.querySelector(selector); } Q = function(selector, within){ var w = within || doc; return w.querySelectorAll(selector); } special = function(str){ return str.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } unspecial = function(str){ return str.replace(/&amp;/g, '&').replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>'); } var out = I('output'), arr = [['ab', 'cd'], ['ef', 'gh'], ['ij', 'kl', 'mn', 'op'], ['qr', 'st'], ['uv', 'wx', 'yz']], outerDiv, innerDiv; arr.forEach(function(a){ outerDiv = M('div'); outerDiv.className = 'demo'; a.forEach(function(v){ // no need for `special` in this case but you may have special characters to escape innerDiv = M('div'); innerDiv.innerHTML = special(v); outerDiv.appendChild(innerDiv); }); output.appendChild(outerDiv); }); }); // end load //]]>
 /* css/external.css */ *{ box-sizing:border-box; } .demo{ border: 1px solid green; padding: 10px; margin: 20px; }
 <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' /> <title>Test Template</title> <link type='text/css' rel='stylesheet' href='css/external.css' /> <script type='text/javascript' src='js/external.js'></script> </head> <body> <div id='output'></div> </body> </html>

Try this:尝试这个:

 <!DOCTYPE html> <html> <head> <style> [id^="demo"] { border: 1px solid green; padding: 10px; margin: 20px; } </style> <div id="section"></div> <script> var arr_args = [["ab", "cd"], ["ef", "gh"], ["ij", "kl"]]; arr_args.forEach(myFunction); function myFunction(item, index) { document.getElementById("section").innerHTML += "<div id=demo" + index + ">" + item[0] + "<br>" + item[1] + "<div>"; } </script> </html>

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

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