我有以下代码,它是 Java servlet、html、javascript/jQuery Web 应用程序的一部分。
<Table border=1>
<Tr>
<Td><button id=Current_1 type=button></button></Td>
<Td><button id=Current_2 type=button></button></Td>
<Td><button id=Current_3 type=button></button></Td>
<Td><button id=Current_4 type=button></button></Td>
<Td><button id=Current_5 type=button></button></Td>
<Td><button id=Current_6 type=button></button></Td>
</Tr>
</Table>
我可以在Java servlet端做什么来获取每个按钮中的所有文本,我正在考虑在单击时有另一个提交按钮,一些jQuery获取所有这些按钮并循环遍历它们以获取每个按钮的文本。
这些按钮中的文本最初没有任何内容,但在应用程序期间用户可以单击并更改值,因此最后我需要为用户提供一种方法来保存这些按钮上的内容并将它们传递给 servlet,这是什么实现这一目标的最佳方法,有示例代码吗?但我最需要帮助的是如何获取按钮并循环访问它们以获取它们的文本?
编辑:可能是我没表达清楚。
If Button_1 has text "B1"
Button_2 has text "B2"
...
Button_6 has text "B6"
用户单击另一个提交按钮后我期望的结果是:B1B2B3B4B5B6
最佳答案
使用 jQuery 制作对象数组相当简单
var buttonData = $('button[id^="Current"]').map(function(){
return {id: this.id, text: $(this).text()};
}).get();
产品:
[
{id:"Current_1", text: "Button #1 Text"},
{id:"Current_2", text: "Button #2 Text"},
....
{id:"Current_6", text: "Button #6 Text"}
]
类选择器可能会更干净,或者从行上的选择器中定位它们
编辑:如果您想要的只是没有分隔符的组合文本,您实际上可以获取整个文本集合,甚至无需循环元素。
$('button[id^="Current"]').text();
对于 jQuery 中的大多数值 getter ,此方法只会返回第一个元素的 vlue,但使用 text()
则返回所有元素
关于javascript - 如何在 Javascript 中一次获取多个按钮的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261698/