从所选元素的文本创建数组

时间:2017-04-02 14:08:55

标签: javascript jquery arrays

如何创建一个数组,其值是所选元素的文本?例如,下面的HTML应该生成数组["test1","test2"]

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Create array</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
        <script type="text/javascript"> 
            $(function(){
                var matched=$('#tbody td.sel');
                console.log(matched);
                console.log(matched.toArray());
                console.log(matched.text());
                //console.log(matched.toArray().text());
            });
        </script>
    </head>
    <body>
        <table>
            <thead>
                <tr><td>Name</td><td>GUID</td></tr>
            </thead>
            <tbody id="tbody">
                <tr><td>Client1</td><td class='sel'>test1</td></tr>
                <tr><td>Client2</td><td class='sel'>test2</td></tr>
            </tbody>
        </table>
    </body>
</html>

3 个答案:

答案 0 :(得分:2)

如果要将jQuery对象转换为数组,则可以使用标准的js Array方法,因此我使用Array.prototype.map迭代输入数组并使用返回的值创建一个新数组。 / p>

$(function() {
  var matched = $('#tbody td.sel')
  console.log(
    matched.toArray().map(function(el) {
      return $(el).text()
    })
  )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <td>Name</td>
      <td>GUID</td>
    </tr>
  </thead>
  <tbody id="tbody">
    <tr>
      <td>Client1</td>
      <td class='sel'>test1</td>
    </tr>
    <tr>
      <td>Client2</td>
      <td class='sel'>test2</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:2)

var arrText = $("#tbody td.sel").map(function(key, val) {
  return val.textContent
})

console.log(arrText)

答案 2 :(得分:0)

这是非jQuery 解决方案。我必须在call的结果上使用getElementsByClassName(),因为它只是&#34;类似数组&#34;。

&#13;
&#13;
a = document.getElementsByClassName('sel');
arr = [];
arr.forEach.call(a, elem => arr.push(elem.innerText));
console.log(arr);
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Create array</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
</head>

<body>
  <table>
    <thead>
      <tr>
        <td>Name</td>
        <td>GUID</td>
      </tr>
    </thead>
    <tbody id="tbody">
      <tr>
        <td>Client1</td>
        <td class='sel'>test1</td>
      </tr>
      <tr>
        <td>Client2</td>
        <td class='sel'>test2</td>
      </tr>
    </tbody>
  </table>
</body>

</html>
&#13;
&#13;
&#13;