Javascript 获取表中的输入值

Javascript 获取表中的输入值,javascript,jquery,html-table,Javascript,Jquery,Html Table,我有一张带按钮的桌子,如下所示;我试图使用jQuery获取td的值 我的桌子: <table class="table" id="Tablesample"> <tr> <th style="display:none;"> @Html.DisplayNameFor(model => model.Id) </th> </tr> @foreach (v

我有一张带按钮的桌子,如下所示;我试图使用jQuery获取td的值

我的桌子:

<table class="table" id="Tablesample">

    <tr>
        <th style="display:none;">
            @Html.DisplayNameFor(model => model.Id)
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td style="display:none;" class="keyvalue">
                <input type="text" name="Key" value="@item.Key" class="form-control" id="configKey" readonly="readonly">
            </td>
            <td>
                <input type="text" name="Key" value="@item.Id" class="form-control" id="configId" readonly="readonly">
            </td>
        </tr>

    }

</table>

<button id="btnSave">Save</button>
但我没有得到任何价值

我也尝试过类似的方法,但也不起作用:

$("#Tablesample tr:gt(0)").each(function () {

    var this_row = $(this);
    var key = $.trim(this_row.find('td:eq(0)').html());
    alert(key);
});

这个问题是由于您的DOM遍历逻辑造成的。首先,
这个
tr
元素,所以
最近('tr')
找不到任何东西。其次,您将从
.keyvalue
text()
中获取字符串值,然后尝试在文本中查找
input
元素,而不是遍历DOM。最后,需要使用
val()
获取输入值

我强烈建议您熟悉jQuery公开的方法及其工作原理:

综上所述,这应该对你有用:

$('#btnSave')。单击(函数(){
$('#Tablesample tr')。每个(函数(){
var keval=$(this.find(“.keyvalue输入”).val();
控制台日志(keval);
});
});

模型

保存
请单击
按钮并创建一个-当然
文本。查找(“输入”).text()无效jQuery-文本是字符串,而.keyvalue是带有输入的单元格。也许您的意思是获取字段的值?这将是$(fieldSelector).val()-而且您没有唯一的IDSNOP,因此不会出现问题。如果我在单个内有多个
input
,则您需要选择您特别需要的
input
-通过
id
class
,例如
var-keval=$(此)。查找(“.keyvalue.your input class here”).val();
我这样做是为了避免未定义的东西,但是
@foreach(模型中的var项){}
它仍然在其中,将
$('Tablesample tr')
更改为
$('Tablesample tbody tr'))
。我建议您也研究选择器的工作原理。作为参考,它与CSS使用的模式相同
$("#Tablesample tr:gt(0)").each(function () {

    var this_row = $(this);
    var key = $.trim(this_row.find('td:eq(0)').html());
    alert(key);
});