按钮

2017-04-05 30 views
0

的点击将值传递给jQuery函数我在HTML页面下表中,我是一个新手,jQuery的按钮

<table class="table table-hover"> 
       <thead> 
        <tr> 
         <th>Name</th> 
         <th>Description</th> 
         <th>Start Date</th> 
         <th>Severity</th> 
         <th>Edit Data</th> 
        </tr> 
       </thead> 
       <tbody id="myTable"> 

         <tr style="display: table-row;"> 
          <td>New Rule</td> 
          <td>New Rule</td> 
          <td>2017-04-04</td> 
          <td>High</td> 
          <td> 
           <button class="btn btn-primary btn-sm editBtn"> 
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 
            Edit 
           </button> 
           <button onclick="window.location =&quot;/EmployeeSpringMVC/delRule/5&quot;" data-method="delete" class="btn btn-danger btn-sm"> 
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 
            Delete 
           </button> 
          </td> 
         </tr> 

       </tbody> 
      </table> 

正如你可以看到有一个编辑按钮,我可以写一个函数下面

$('.editBtn').click(function(){ 
     alert("test"); 
    }); 

我还需要数据的特定行中的函数一些处理给出认识到点击此按钮。我如何从表格中获取这些数据?如果有更好的方法,请随时提出建议。

我看到here这个问题,但我不明白这个答案的说法。

var id = $(this).attr('id'); 

如何将id传递给函数。什么在这里指定了id。

<input id="btn" type="button" value="click" /> 
+0

数据你指的是哪个? –

+1

在实现本地'.closest()'方法的现代浏览器中,$(this).closest(“tr”)'在jQuery或'this.closest(“tr”)'中,如果需要可以进行多边填充。在这两者中,'this'是绑定处理程序的元素,'.closest()'从这个点开始遍历祖先,直到找到与“tr”选择符相匹配的元素。 – 2017-04-05 13:28:14

+0

中的数据,其中该按钮存在 – Manesh

回答

1

,因为你可能需要在一行中的所有<td>,除了当前我会建议使用最接近<td>siblings()方法:

$('.editBtn').click(e => { 
 
    e.preventDefault(); 
 
    const $td = $(e.target).closest('td'); 
 
    const fields = Array.from($td.siblings('td').map((i, e) => $(e).text())); 
 
    console.log(fields); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table class="table table-hover"> 
 
    <thead> 
 
    <tr> 
 
     <th>Name</th> 
 
     <th>Description</th> 
 
     <th>Start Date</th> 
 
     <th>Severity</th> 
 
     <th>Edit Data</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody id="myTable"> 
 

 
    <tr style="display: table-row;"> 
 
     <td>New Rule</td> 
 
     <td>New Rule</td> 
 
     <td>2017-04-04</td> 
 
     <td>High</td> 
 
     <td> 
 
     <button class="btn btn-primary btn-sm editBtn"> 
 
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 
 
            Edit 
 
           </button> 
 
     <button onclick="window.location =&quot;/EmployeeSpringMVC/delRule/5&quot;" data-method="delete" class="btn btn-danger btn-sm"> 
 
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 
 
            Delete 
 
           </button> 
 
     </td> 
 
    </tr> 
 

 
    </tbody> 
 
</table>