如何使用ID或数据属性

时间:2018-05-10 09:53:51

标签: javascript jquery

HI在此代码中只有点击事件的第一个按钮正在工作,但是当我点击第二个没发生时我不想使用input:button因为我有多个按钮在页面上..



   <table border="1">
 <tr>
      <td>Name</td>
      <td>Email</td>
      <td>phone</td>
      <td>Btn</td>
    </tr>
    <tr>
      <td>user 1</td>
      <td>user1@mail.com</td>
      <td>123456</td>
      <td>
        <button id="btnids" data-id="a1" value="a1">active</button>
       </td>
    </tr>
     <tr>
      <td>user 1</td>
      <td>user1@mail.com</td>
      <td>123456</td>
      <td>
        <button id="btnids" data-id="a2" value="a2">active</button>
       </td>
    </tr>
     <tr>
      <td>user 1</td>
      <td>user1@mail.com</td>
      <td>123456</td>
      <td>
        <button id="btnids" data-id="a3" value="a3">active</button>
       </td>
    </tr>
    </table>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
          $("#btnids").click(function(){
            alert($(this).val());
          });
    });
</script>
&#13;
&#13;
&#13; 谢谢!

2 个答案:

答案 0 :(得分:1)

属性id应该是唯一的。将属性从id更改为class

&#13;
&#13;
$(document).ready(function(){
    $(".btnids").click(function(){
      alert($(this).val());
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tr>
    <td>Name</td>
    <td>Email</td>
    <td>phone</td>
    <td>Btn</td>
  </tr>
  <tr>
    <td>user 1</td>
    <td>user1@mail.com</td>
    <td>123456</td>
    <td>
      <button class="btnids" data-id="a1" value="a1">active</button>
     </td>
  </tr>
   <tr>
    <td>user 1</td>
    <td>user1@mail.com</td>
    <td>123456</td>
    <td>
      <button class="btnids" data-id="a2" value="a2">active</button>
     </td>
  </tr>
   <tr>
    <td>user 1</td>
    <td>user1@mail.com</td>
    <td>123456</td>
    <td>
      <button class="btnids" data-id="a3" value="a3">active</button>
     </td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用class而不是ID,因为元素ID在整个文档中应该是唯一的。

<table border="1">
 <tr>
      <td>Name</td>
      <td>Email</td>
      <td>phone</td>
      <td>Btn</td>
    </tr>
    <tr>
      <td>user 1</td>
      <td>user1@mail.com</td>
      <td>123456</td>
      <td>
        <button class="btnids" data-id="a1" value="a1">active</button>
       </td>
    </tr>
     <tr>
      <td>user 1</td>
      <td>user1@mail.com</td>
      <td>123456</td>
      <td>
        <button class="btnids" data-id="a2" value="a2">active</button>
       </td>
    </tr>
     <tr>
      <td>user 1</td>
      <td>user1@mail.com</td>
      <td>123456</td>
      <td>
        <button class="btnids" data-id="a3" value="a3">active</button>
       </td>
    </tr>
    </table>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
          $(".btnids").on('click',function(){
            alert($(this).val());
          });
    });
</script>