【问题标题】:How to correctly retrieve and change the text's value stored from an array in jQuery?如何正确检索和更改存储在 jQuery 数组中的文本值?
【发布时间】:2021-11-25 08:42:57
【问题描述】:

我正在尝试使用存储在数组中的字符串值更改每个 <th> 标记。如果它到达数组长度的末尾,它只会重置我已经实现的计数器。我希望能够保持循环和更改每个标题文本值,直到表格结束。我已经尝试了几次代码尝试来更改和输出下面的标题文本(但没有成功;也没有控制台错误输出):

$(this).text() == headerTitleArr[headerIndex];
//$(this).text(headerTitleArr[headerIndex])[thIndex];
//$(this).css("content", headerTitleArr[headerIndex]);

我调试了代码以查看两个值都返回了什么,并且它们都返回了字符串值,但是由于某种原因,数组headerTitleArr[headerIndex] 中的值没有被传递给$(this).text(),这应该是DOM tr.table tr > th 的选择器,因此与您在 console.log 输出中看到的相同。

这是我的jsfiddle 问题。

代码片段:

if (window.matchMedia('(max-width: 2799px)').matches) {
  // do functionality on screens smaller than 2799px

  var headerTitleArr = ["Players","Stamina","Home Runs"];
  var headerTitleArrLength = 2;
  var mainChart = $("#chart1");
  var headerIndexCount = 0;
  // loop thru each of the tr.table-tr rows tracked by index and change the th text's index with the header text value
  $("#chart1 tr.table-tr > th").each(function(thIndex) {
    headerIndex = headerIndexCount;

    // TO FIX
    $(this).text() == headerTitleArr[headerIndex];
    //$(this).text(headerTitleArr[headerIndex])[thIndex];
    //$(this).css("content", headerTitleArr[headerIndex]);
    
    headerIndexCount++;

    // if headerIndex equals to the length of the array, reset value
    if (headerIndex == headerTitleArrLength) {
      headerIndexCount = 0; // reset value
    }
  });
}

【问题讨论】:

    标签: javascript html jquery css html-table


    【解决方案1】:

    我想是这里:

    改变

    $(this).text() == headerTitleArr[headerIndex];

    到

    $(this).text(headerTitleArr[headerIndex]);

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 2019-11-18
      • 2012-10-23
      • 2014-03-02
      • 1970-01-01
      • 2016-08-22
      相关资源
      最近更新 更多