如何在Javascript中一次获取多个按钮的文本

How to get several buttons' text at once in Javascript?

本文关键字:获取 一次 按钮 文本 Javascript      更新时间:2023-09-26

我有以下代码,它是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中的大多数值获取者,此方法将仅返回第一个元素的vlue,但text()返回所有

正如你提到的,你可以使用另一个按钮来获取每个按钮的文本。只需使用一个公共类并遍历它们

$(document).ready(function(){
   $("#Current_7").click(function(){
      $(".myButton").each(function(){
      console.log($(this).text())
      })   
   })
})

工作示例

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function () {
        $('button[id^="Current"]').each(function(){
        console.info($(this).attr('id') + '----' + $(this).text())        
        });
    });
</script>
</head>
<body>
    <Table border=1>
    <Tr>
      <Td><button id=Current_1 type=button>button_1</button></Td>
      <Td><button id=Current_2 type=button>button_2</button></Td>
      <Td><button id=Current_3 type=button>button_3</button></Td>
      <Td><button id=Current_4 type=button>button_4</button></Td>
      <Td><button id=Current_5 type=button>button_5</button></Td>
      <Td><button id=Current_6 type=button>button_6</button></Td>
    </Tr>                                
  </Table>
</body>
</html>