jQuery将click函数添加到多个输入

时间:2019-03-14 16:43:40

标签: javascript jquery

我想要一个函数来响应对输入字段的每个实例的单击。但是该函数仅响应对输入的第一个实例的单击。

HTML是:

<table class="table">
  <tr>
     <td><input id="show-output" type="button" value=261 /></td>
     <td>mhour test202</td>
  </tr>
  <tr>
     <td><input id="show-output" type="button" value=260 /></td>
     <td>mhour test145</td>
  </tr>
</table>

功能是

$('#show-output').click(function(e) {
  alert("hi");
});

A fiddle for this

1 个答案:

答案 0 :(得分:1)

将您的ID更改为类,因为ID应该始终只在页面上出现一次。

$('.show-output').click(function(e) {
  alert("hi");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table">
  <tr>
     <td><input class="show-output" type="button" value=261 /></td>
     <td>mhour test202</td>
  </tr>
  <tr>
     <td><input class="show-output" type="button" value=260 /></td>
     <td>mhour test145</td>
  </tr>
</table>