如何使用jquery / javascript连接来自单独元素的字符串



我想连接来自 2 个单独元素的字符串并将它们存储在变量中。

目前我的代码将变量设置为等于:"每日

:1070300,每周:1070300,每月:1070300">

我的目标是使控制台中的变量等于:"每日:10,每周:70,每月:300">

      $(document).ready(function() {
        var str = '';
        $('tbody > tr').each(function() {
          $(this).find('.key').each(function() {
            str += $(this).text() + ": " + $(this).parents().siblings('tr').find('.value').text() + ", ";
          })
        });
        console.log(str);
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <th class="key">Daily</th>
      <th class="key">Weekly</th>
      <th class="key">Monthly</th>
    </tr>
    <tr>
      <td class="value">10</td>
      <td class="value">70</td>
      <td class="value">300</td>
    </tr>
  </tbody>
</table>

谢谢大家的帮助!

每次通过key循环时,您都会抓取所有三个value单元格的内容(因为$(this).parents().siblings('tr').find('.value')匹配所有三个单元格(。有很多方法可以解决这个问题,但我看到的一个简单方法是使用内部循环上的index参数来选择与当前key对应的value单元格(使用 jQuery 的 eq 函数(:

  $(document).ready(function() {
    var str = '';
    $('tbody > tr').each(function() {
      $(this).find('.key').each(function(index) {
        str += $(this).text() + ": " + $(this).parents().siblings('tr').find('.value').eq(index).text() + ", ";
      })
    });
    console.log(str);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
      <th class="key">Daily</th>
            <th class="key">Weekly</th>
            <th class="key">Monthly</th>
        </tr>
        <tr>
            <td class="value">10</td>
            <td class="value">70</td>
            <td class="value">300</td>
        </tr>
    </tbody>
</table>

当你不断在循环中查找内容时,代码效率非常低。因此,修复它以读取索引将起作用,它只会导致代码执行比所需更多的工作。

如何改进。使用索引查找两行和一个循环。

var keys = $("table .key")  //select the keys
var values = $("table .value")  //select the values
var items = []  // place to store the pairs
keys.each(function(index, elem){ //loop over the keys
   items.push(elem.textContent + " : " +  values[index].textContent)  // read the text and use the index to get the value
})
console.log(items.join(", "))  // build your final string by joing the array together
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <th class="key">Daily</th>
            <th class="key">Weekly</th>
            <th class="key">Monthly</th>
        </tr>
        <tr>
            <td class="value">10</td>
            <td class="value">70</td>
            <td class="value">300</td>
        </tr>
    </tbody>
</table>

收集.key并将类.value到一个 NodeList 中,将 NodeList 转换为数组。然后将 2 个数组合并到存储在对象文本中的键/值对中。最后将对象转换为字符串,以便可以显示它。

演示

详细信息在演示中注释

// Collect all th.key into a NodeList and turn it into an array 
var keys = Array.from(document.querySelectorAll('.key'));
// As above with all td.value
var vals = Array.from(document.querySelectorAll('.value'));
function kvMerge(arr1, arr2) {
  // Declare empty arrays and an object literal
  var K = [];
  var V = [];
  var entries = {};
  
  /* map the first array...
  || Extract text out of the arrays
  || Push text into a new array
  || Then assign each of the key/value pairs to the object
  */
  arr1.map(function(n1, idx) {
    var txt1 = n1.textContent;
    var txt2 = arr2[idx].textContent;
    K.push(txt1);
    V.push(txt2);
    entries[K[idx]] = V[idx];
  });
  return entries;
}
var result = kvMerge(keys, vals);
console.log(result);
// Reference the display area
var view = document.querySelector('.display');
// Change entries object into a string
var text = JSON.stringify(result);
// Clean up the text
var final = text.replace(/[{"}]{1,}/g, ``);
// Display the text
view.textContent = final
<table>
  <tbody>
    <tr>
      <th class="key">Daily</th>
      <th class="key">Weekly</th>
      <th class="key">Monthly</th>
    </tr>
    <tr>
      <td class="value">10</td>
      <td class="value">70</td>
      <td class="value">300</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td class='display' colspan='3'></td>
    </tr>
  </tfoot>
</table>

您也可以使用唯一 id 来解决这个问题,如下所示:

$(document).ready(function() {
  var str = '';
  $('tbody > tr').each(function() {
    $(this).find('.key').each(function() {
      var index = $(this).attr('id').slice(3)
      str += $(this).text() + ": " + $('#value'+index).text() + ", ";
    })
  });
  console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <th class="key" id="key1">Daily</th>
      <th class="key" id="key2">Weekly</th>
      <th class="key" id="key3">Monthly</th>
    </tr>
    <tr>
      <td class="value" id="value1">10</td>
      <td class="value" id="value2">70</td>
      <td class="value" id="value3">300</td>
    </tr>
  </tbody>
</table>

相关内容

最新更新