如何在javascript上获取单元格值确认?

时间:2015-10-27 17:09:00

标签: javascript jquery

我有一个html代码,我想点击删除删除当前行,然后显示确认“你要删除[名称]?” 那么,当我使用Jquery点击删除时,如何获取名称值以确认?

<table id="tblInfo">

    <thead>
    <tr>
        <th>#</th>
        <th>Name</th>
        <th>Birthday</th>
        <th></th>
    </tr>
    </thead>

    <tbody>
    <tr>
        <td>1</td>
        <td>Name1</td>
        <td>01/01/1990</td>
        <td>
            <a href="#" class="btnView" >View</a>
            <a href="#" class="btnDelete">Delete</a>
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>Name2</td>
        <td>01/01/1990</td>
        <td>
            <a href="#" class="btnView">View</a>
            <a href="#" class="btnDelete">Delete</a>
        </td>
    </tr>
    </tbody>

    <tfoot>
    <tr>
        <td></td>
        <td><input type="text" name="" value="" size="25" /></td>
        <td><input type="text" name="" value="" size="25" /></td>
        <td>
            <a href="#" class="btnAdd">Add</a>
        </td>
    </tr>
    </tfoot>
</table>

2 个答案:

答案 0 :(得分:0)

您需要找到最接近的tr元素,然后从第二个td元素中获取文本。

这是解决这个问题的工作方式。

$(document).ready(function(){
    $('.btnDelete').click(function(){
        var selectedName = $($(this).closest("tr").children()[1]).text(); 
        console.log("Selected name is "+ selectedName);
    });
});

https://jsfiddle.net/rbdharnia/03gbLhu4/1/

答案 1 :(得分:0)

演示:http://jsfiddle.net/1qda1jpx/1/

$(document).ready(function() {
    $("#tblInfo").on("click", ".btnDelete", function() {
        var $this = $(this);
        var name = $this.closest("tr").find("td:nth-child(2)").text(); // gets the name of the row
        if (confirm("Do you want to delete" + name + "?"))
        { $this.closest('tr').remove(); } // upon confirmation, remove the row
    });
});