javascript - 迭代 td 中的每个输入字段

标签 javascript jquery html-table

我正在尝试使用 jQuery 迭代表中的每个输入字段。

<table border="1">
    <tbody><tr>
        <td><input value="0"><input value="1" type="hidden"></td>
        <td><input value="2"><input value="3" type="hidden"></td>
        <td><input value="4"><input value="5" type="hidden"></td>
        <td><input value="6"><input value="7" type="hidden"></td>
    </tr>
    <tr>
        <td><input value="7"><input value="8" type="hidden"></td>
        <td><input value="9"><input value="10" type="hidden"></td>
        <td><input value="11"><input value="12" type="hidden"></td>
        <td><input value="13"><input value="14" type="hidden"></td>
    </tr>

</tbody></table>
<button onclick="test()">Click me!</button>

最佳答案

使用each() 用于迭代 dom 元素

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element. ( Taken from https://api.jquery.com/each/ )

function test() {
  $('table td input').each(function() {
    console.log(this.value,this.type);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
  <tbody>
    <tr>
      <td>
        <input value="0">
        <input value="1" type="hidden">
      </td>
      <td>
        <input value="2">
        <input value="3" type="hidden">
      </td>
      <td>
        <input value="4">
        <input value="5" type="hidden">
      </td>
      <td>
        <input value="6">
        <input value="7" type="hidden">
      </td>
    </tr>
    <tr>
      <td>
        <input value="7">
        <input value="8" type="hidden">
      </td>
      <td>
        <input value="9">
        <input value="10" type="hidden">
      </td>
      <td>
        <input value="11">
        <input value="12" type="hidden">
      </td>
      <td>
        <input value="13">
        <input value="14" type="hidden">
      </td>
    </tr>

  </tbody>
</table>
<button onclick="test()">Click me!</button>

关于javascript - 迭代 td 中的每个输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33727694/

相关文章:

javascript - 使用 Node 执行.exe文件仅在 Protractor 中运行一次

javascript - jquery数组到字符串以显示文本框输入

javascript - Rails 服务器告诉我---找不到类型为 'jquery-ui/datepicker' 的文件 'application/javascript'

html - 使用 colspan 时如何修复填充 Twitter Bootstrap 单元格表

javascript - 元组数组的 JSON 模式

javascript - 哪个更适合标识通过菜单打开的窗口,outerWindowID 或 currentInnerWindowID?

HTML css 表未对齐列

jquery - 对表元素的重复 ajax 请求

javascript - 根据状态变化仅将样式应用于一个 div

javascript - 用 JQuery 替换 img