table如下:
<table  > 
  <tr> 
   <td>1</td>
  <td><input type=text  value="数据1" /></td>
  <td><input type=button  onclick="GetTest()" value="获取" /></td>
  </tr> 
  <tr>
   <td>2</td>
   <td><input type=text  value="数据2" /></td>
   <td><input type=button  onclick="GetTest()" value="获取" /></td>
  </tr> 
</table>table是通过后台动态输出生成,我想通过点击每一行的button,然后获取当前行的另一列的数据值,比如获取上表的点击行的“数据1”、“数据2”,不知如何写GetTest()函数

解决方案 »

  1.   

    <script type="text/javascript">
    $(function(){
    $("table tr td").each(function(){
    $(this).find("[type=button]").click(function(){
    alert($(this).parent().parent().find("[type=text]").val());
    });
    });
    });
      </script>
      

  2.   

    function GetTest(obj) {
                alert($(obj).parent().prev().children().val());
            }onclick="GetTest(this)" 
      

  3.   


    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
        <title></title>
        <script type="text/javascript">
            $(function () {
                $("input[type=button]").on("click", function () {
                    alert($(this).parent().prev().find("input").val());
                });
            })
        </script>
    </head>
    <body>
        <div>
            <table>
                <tr>
                    <td>
                        1
                    </td>
                    <td>
                        <input type="text" value="数据1" />
                    </td>
                    <td>
                        <input type="button"  value="获取" />
                    </td>
                </tr>
                <tr>
                    <td>
                        2
                    </td>
                    <td>
                        <input type="text" value="数据2" />
                    </td>
                    <td>
                        <input type="button"  value="获取" />
                    </td>
                </tr>
            </table>
        </div>
    </body>
    </html>
      

  4.   

    最好的方式  还是在生成的时候。为元素生成出类似坐标的id
    比如你动态生成每行的时候用的是for(var i =1; i<数据.Rows.count; i++){??}
    每个循环生成一个<td id="列名字+i">  
    这里你可以给i前面或后面加些东西(比如:id_1,name_2,button_1)
    你点击button1的时候。把行号过滤出来。
    比如你点击的第4行。想得到name列。
    在所有button的点击事件里这样写:
    $(???).click(function(){
         var rows_index = $(this).attr("id").spit("_")[1];
        var name = $("#name"+rows_index).val();
        alert(name);
    })