Javascript更改所有span元素的innerHTML

时间:2015-12-18 15:43:02

标签: javascript for-loop

预期行为:按下按钮,每个范围中包含的文字将更改为"更新"

实际行为:按下按钮时,似乎没有任何变化。

JSFiddle:https://jsfiddle.net/jrj0y5kd/

CSS

span {
  border: 1px solid black;
  padding: 5px;
}

td {
  padding: 10px;
}

div {
  padding: 10px;
  border: 2px solid black;
  display: inline-block;
  text-align: center;
}

HTML

<div style="container">
  <button value="UPDATE" onClick="update()">UPDATE</button>
  <table>
    <tr>
      <td>
        <span>1A</span>
      </td>
      <td>
        <span>1B</span>
      </td>
      <td>
        <span>1C</span>
      </td>
    </tr>
    <tr>
      <td>
        <span>2A</span>
      </td>
      <td>
        <span>2B</span>
      </td>
      <td>
        <span>2C</span>
      </td>
    </tr>
    <tr>
      <td>
        <span>3A</span>
      </td>
      <td>
        <span>3B</span>
      </td>
      <td>
        <span>3C</span>
      </td>
    </tr>
  </table>
</div>

的Javascript

function update() {
  var spans = document.getElementsByTagName('span');
  for (var i = 0; i < spans.length; i++) {
    spans[i].innerHTML = "UPDATED!";
  };
}

2 个答案:

答案 0 :(得分:4)

您必须全局定义该功能。在jsFiddle中,您可以使用JavaScript块右上角的小设置图标指定此行为。请参阅此更新的小提琴:https://jsfiddle.net/jrj0y5kd/2/

<html>
    <head>
       <script>
          function update(){
              // your code
          }
       </script>
     </head>
<body>
    <button value="UPDATE" onclick="update()">UPDATE</button>
</body>
</html>

'load type'下的选项需要设置为:no wrap - in head

答案 1 :(得分:-1)

更新未定义。我认为你将函数定义为迟到或者什么

<script>
function update() {
  var spans = document.getElementsByTagName('span');
    for (var i = 0; i < spans.length; i++) {
      spans[i].innerHTML = "UPDATED!";
    };
}
</script>

<div style="container">
<button value="UPDATE" onclick="update()">UPDATE</button>
<table><tr><td>
<span>1A</span>
</td><td>
<span>1B</span>
</td><td>
<span>1C</span>
</td></tr><tr><td>
<span>2A</span>
</td><td>
<span>2B</span>
</td><td>
<span>2C</span>
</td></tr><tr><td>
<span>3A</span>
</td><td>
<span>3B</span>
</td><td>
<span>3C</span>
</td></tr></table></div>

有效