gpt4 book ai didi

javascript - 如何获取表中的输入值?

转载 作者:行者123 更新时间:2023-12-01 01:00:46 25 4
gpt4 key购买 nike

我有一个包含动态行的表格,每行在其按钮旁边都包含一个输入(在第三个单元格中)。

下面的代码代表我的表格的一行:

window.getKey = function(ele) {

var row = ele.closest('tr');

console.log("cell 0: " + row.cells[0].textContent);
console.log("cell 1: " + row.cells[1].textContent);
console.log("cell 2: " + row.cells[2].children[0].value);
}
<table class="table table-striped table-bordered text-center table-hover" id="tbl_posts">
<tr class="satr">
<th class="colu">Username</th>
<th class="colu">Post</th>
<th class="colu">Decode</th>
</tr>
<tr>
<td>
<p>Mike</p>
</td>
<td>
<p>Content</p>
<td>
<div>
<input id="key_input" type="number" placeholder="Enter number" />
<div>
<button class="btn btn-outline-secondary" id="decode" type="submit" onclick="getKey(this)">Decode</button>
</div>
</div>
</td>

如您所见,console.log() 显示了除第三个单元格之外的单元格的内容。其他问题对我没有帮助(例如:How to retrieve value of input type in a dynamic table)

如何访问第三个单元格中的输入值?

最佳答案

根据您的 HTML 代码,row.cells[2].children[0].value 获取 div 的值,而不是 input。要获取输入的值,您可以使用:

  • row.cells[2].children[0].children[0].value
  • row.cells[2].querySelector("input").value

代码:

window.getKey = function(ele) {
var row = ele.closest('tr');

console.log("cell 0: " + row.cells[0].textContent);
console.log("cell 1: " + row.cells[1].textContent);
console.log("cell 2: " + row.cells[2].querySelector("input").value);
}
<table class="table table-striped table-bordered text-center table-hover" id="tbl_posts">
<tr class="satr">
<th class="colu">Username</th>
<th class="colu">Post</th>
<th class="colu">Decode</th>
</tr>
<tr>
<td>
<p>Mike</p>
</td>
<td>
<p>Content</p>
</td>
<td>
<div>
<input id="key_input" type="number" placeholder="Enter number" />
<div>
<button class="btn btn-outline-secondary" id="decode" type="submit"
onclick="getKey(this)">Decode</button>
</div>
</div>
</td>
</tr>
</table>

关于javascript - 如何获取表中的输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56102837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com