单击按钮从html表中获取行

时间:2018-10-19 18:26:48

标签: javascript jquery html ajax

所以,我有一个带有更新按钮的表,我希望能够从单击的行按钮中获取列。

下面是表格的html代码

<table class="table table-hover" style="width: 99%">
        <thead class="thead-dark" align="center">
            <tr>
                <th>ID</th>
                <th>Trainee Class</th>
                <th>Start Date</th>
                <th>Edit</th>
                <th>Trainees</th>
            </tr>
        </thead>
        <tbody align="center">
            <tr>
                <td class="nr">J001</td>
                <td>Java Stream</td>
                <td>01-April-2018</td>
                <td><button onclick="updateData()">Update</button>
                    <button>Remove</button></td>
                <td><button>View</button></td>
            </tr>
 <table>

因此,当我单击更新时,我想获取“ J001”(更新按钮行的第一列)。

我在下面尝试过,但是没有获取。

function updateData(){
     var $item = $(this).closest("tr")   
                 .find(".nr")    
                 .text();        

     alert($item);      
}

任何帮助或建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

您必须在更新函数调用中传递 this

您的HTML应该是

<table class="table table-hover" style="width: 99%">
        <thead class="thead-dark" align="center">
            <tr>
                <th>ID</th>
                <th>Trainee Class</th>
                <th>Start Date</th>
                <th>Edit</th>
                <th>Trainees</th>
            </tr>
        </thead>
        <tbody align="center">
            <tr>
                <td class="nr">J001</td>
                <td>Java Stream</td>
                <td>01-April-2018</td>
                <td><button onclick="updateData(this)">Update</button>
                    <button>Remove</button></td>
                <td><button>View</button></td>
            </tr>
 <table>

jQuery函数应该是

function updateData(e){
     var $item = $(e).closest("tr")   
                 .find("td:first")    
                 .text(); 
     alert($item);      
}