我的 HTML 中有这个表格:
<table class="dataTable" id="repaymentShedule">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
</tr>
</thead>
<tbody data-bind="foreach: creditDetails">
<tr>
<td class="paymentDate" data-bind="text: dateOfPayment"></td>
<td class="startBalance" data-bind="text: beginingBalance"></td>
<td class="monthlyInt" data-bind="text: monthlyInterest"></td>
<td class="principal"><input data-bind="value: princpalPayment"></input></td>
<td class="monthlyInst" data-bind="text: monthlyInstallment"></td>
<td class="remainingBalance" data-bind="text: endingBalance"></td>
<td class="paid"><input type="checkbox" data-bind="checked: isPaid, disable: isPaid, click: testFunc, value: true"></td> <!-- value: true moje da ne e nujno -->
<td class="currentDate" data-bind="text: currentDate"></td>
</tr>
</tbody>
</table>
这些值来自 knockout js
绑定(bind)。
我正在尝试使用以下函数获取 principal
类的所有值:
updateValues = function(){
$("tbody").find("tr").each(function() {
var principal = $(this).find('td.principal').val();
console.log(principal);
});
};
控制台返回:(空字符串)
编辑:
只需将 .val()
更改为 .text()
paymentDate
类上就可以正常工作。
我很确定我没有以正确的方式获取值,或者绑定(bind)不允许我获取当前值,但我真的无法发现问题
最佳答案
你需要这样做:
var principal = $(this).find('td.principal :input').val();
使用 principal
类获取表格单元格内 input
元素的值。
此外,根据 .val() API Documentation :-
The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.
因此,您在使用代码时会在控制台中收到空字符串。
The above function works without any problems on the paymentDate class only by changing the .val() to .text()
这也解释了为什么在将 paymentDate
表格单元格的 .val()
更改为 .text()
后,您获得了正确的值,因为它内部没有任何 input
元素。
关于javascript - 为什么我无法获取输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19558832/