使用Java脚本更改多个元素的内容而无需for循环

时间:2018-07-23 02:35:12

标签: javascript html class

我正在尝试使用以下方法更改具有相同ID的多个元素的内容:

window.onload = function() {
document.getElementById('price_01').innerHTML = price_01;
document.getElementById('dimension_01').innerHTML = dimension_01;
}

<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <script type="text/javascript">
    var price_01 = '$8000';
    var dimension_01 = '10m';
    window.onload = function() {
    document.getElementById('price_01').innerHTML = price_01;
    document.getElementById('dimension_01').innerHTML = dimension_01;
	}
  </script>
<body>

<div class="w3-container">
  <h2>W3.CSS Modal</h2>
  <div class="w3-container">
    <table class="table">
        <tbody>
          <tr>
            <td>Price:</td>
            <td id='price_01'></td>
          </tr>
          <tr>
            <td>Dimension:</td>
            <td id='dimension_01'></td>
          </tr>
        </tbody>
    </table>
  </div>
  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal</button>
  <div id="id01" class="w3-modal">
    <div class="w3-modal-content">
      <div class="w3-container">
        <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">&times;</span>
        <div class="w3-container">
          <table class="table">
              <tbody>
                <tr>
                  <td>Price:</td>
                  <td id='price_01'></td>
                </tr>
                <tr>
                  <td>Dimension:</td>
                  <td id='dimension_01'></td>
                </tr>
              </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
            
</body>
</html>

但是,似乎代码无法正常工作,因为每个元素只能有一个唯一的ID。没有for循环和类,是否有解决此问题的更优雅的解决方案?我有很多要填充的元素,我真的不想为每个元素编写一个for循环。

0 个答案:

没有答案