单击提交按钮时,JavaScript代码输出两次

JavaScript code outputs twice when clicking submit button

本文关键字:两次 输出 代码 按钮 提交 JavaScript 单击      更新时间:2023-09-26

由于某种原因,下面示例中的代码在单击按钮时不断输出两次,我无法找出原因。

var onClick = function() {
  var cars = ["Saab", "Volvo", "BMW"];
  var rows = "";
  rows += "<tr><td> " + cars[0] + " </td></tr>";
  $(rows).appendTo("#list tbody");
};
$('#button').click(onClick);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />
<table id="list" class="table table-bordered; sortable">
  <thread>
    <tr>
      <th>Group Name</th>
    </tr>
  </thread>
  <tbody></tbody>
</table>

JSFiddle。

这是因为您有一个拼写错误:<thread>应该是<thead>

这个拼写错误导致您的表结构无效,使浏览器尝试将其更正为:

<thread></thread>
<table id="list" class="table table-bordered; sortable">
  <tbody>
    <tr>
      <th>Group Name</th>
    </tr>
  </tbody>
  <tbody></tbody>
</table>

因此,您的<table>具有两个<tbody>元素,使"#list tbody"选择器产生

这是因为您的表中有拼写错误。我在这个更新的Fiddle中修复了它。

<input type="button" id="button" value="Click Me" />
         <table id="list" class="table table-bordered; sortable">
                <thead>
                    <tr>
                        <th>Group Name</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>