【问题标题】:Getting separated strings from array information从数组信息中获取分离的字符串
【发布时间】:2014-08-02 16:30:55
【问题描述】:

以下代码将来自 html 表的选中复选框的行信息存储到一个数组中:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>

    <script>
    function myFunc() {
    var myValues = new Array();

    $.each($("input[name='selection[]']:checked").closest("td").siblings("td"),
           function () {
                myValues.push($(this).text());
           });

       alert("values: " + myValues.join("  "));

     }

  </script>

    <table border="2">
    <tr>
      <th>Select</th>
        <th>ID</th>
        <th>NAME</th>
        <th>JOB</th>
    </tr>
    <tr>
       <td align="center"><input type="checkbox" class="selection" name="selection[]"></td> 
        <td>11</td>
        <td>John</td>
         <td>Doctor</td>
    </tr>
    <tr>
        <td align="center"><input type="checkbox" class="selection" name="selection[]"></td>
        <td>102</td>
        <td>Anne</td>
        <td>Pilot</td>
    </tr>
    <tr>
        <td align="center"><input type="checkbox" class="selection" name="selection[]"></td>
        <td>203</td>
        <td>Laura</td>
        <td>Teacher</td>
    </tr>

    </tr>
    </table>
     <input type="button" value="get it" onclick="javascript:myFunc(); return false;">

现在我需要将选定的 id 放在逗号分隔的字符串中(如果选中的所有复选框都是:str1="11,102,203";

ID 加上另一个字符串中所选行中的其余信息(如果选中的所有复选框都是:str2 = "11, John, Doctor,102, Anne,Pilot, 203, Laura, Teacher";)。

我不知道该怎么做。我正在考虑将键添加到 myValues 数组,但我不知道这是否是一个好方法(并且不知道如何去做.. 对 jquery 来说太新了:()

【问题讨论】:

  • 使用 fn.map 并加入它api.jquery.com/map fn.map 的文档包含您正在寻找的示例 btw
  • 提供有关您希望 2 个字符串的外观的更多信息,要求不明确。 Id 的字符串应该看起来像 selectedIdsStr ="11,203"。另一个字符串将如何看起来像 otherInfoStr="11 John Doctor,203 Laura Teacher"?
  • 你是对的。编辑了我的帖子。谢谢,桑吉夫

标签: jquery arrays checkbox html-table row


【解决方案1】:

已解决:看看这是否对您有帮助

虽然我不确定你希望这 2 个字符串是什么样子,但我已经为你创建了一个演示 在选定的行中获取不同的值。 我建议你遍历选中的复选框 td 并使用 next() 函数在行中获取不同的值。

$.each($("input[name='selection[]']:checked").closest("td"),function (index,item) {
...
});

JS Fiddle 演示 http://jsfiddle.net/kTDPK/

对于字符串输出检查浏览器的控制台。

【讨论】:

  • 我在 demo.FYI 中做了一些小的优化来优化,我们可以通过 Jquery 中的许多其他方式来实现这个结果,比如使用 tr children() 或 td兄弟姐妹() 或 :nth-child()选择器,但 next() 更适合您的场景,因为您的表中只有几列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 2015-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多