javascript - slice() 在控制台中正确返回,但字符串在 <td> 中未被替换

标签 javascript html angularjs bootstrap-4

我在控制台中看到了我期望的子字符串,但原始字符串在 HTML 中没有被更改。

最终结果应 chop 每个表中的任何长文本 <td> .

注意:我不想在每个 <td> 的 HTML 中使用 limitTo因为此解决方案是对使用数千个表格的大型应用程序的测试,我们不想手动添加对较长内容的限制。

这是我遇到问题的 JS 片段:(我留下了评论,因为它们是解决问题的相关尝试)

 // force table content to wrap to next line after 30 characters (limit set in CSS)
        for (var i = 0; i < tableTD.length; i++){
            var text = tableTD[i].textContent;
            //var truncatedText = '';
            if(text.length > 30 ) {
                tableTD[i].classList.add('wrap');
                truncate(text, 60);
                //truncatedText = truncate(text, 60);
                //return truncatedText;

            } else { tableTD[i].classList.add('nowrap'); }

        }

        // testing
        // function truncate(str, num){
        //     var truncatedStr = '';
        //     if (str.length > num) {
        //         truncatedStr = str.slice(0, (num - 2)) + '...'
        //     }
        //     return truncatedStr;
        // };

        function truncate(str, num){
            truncateStr = str.slice(0, (num - 2)) + '...';

            return truncateStr
        }

这是我在控制台中看到的: text truncated in console but not in HTML

这是完整的 JS(angularjs 1.6.9):

var app = angular.module('myApp', []);
app.controller('karinasSandboxCtrl', function($scope)
{
    // create some lines of data
    $scope.records = [
        {
            "Name" : "Peter Rabbit",
            "Age" : "34",
            "Hobbies" : "Peter Rabbit: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".01",
            "NumberTwo" : "2828.09",
            "NumberThree" : "33829749.00",
            "NumberFour" : "379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" : "Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour" : "Four Four Four Four",
            "Notes" :"Peter Rabbit: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        } , {
            "Name" :"Sailor Moon",
            "Age" :"22",
            "Hobbies" : "Sailor Moon: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".11",
            "NumberTwo" :"28.09",
            "NumberThree" : "33829749.00",
            "NumberFour":"379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" :"Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour":"Four Four Four Four",
            "Notes" :"Sailor Moon: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        } , {
            "Name" : "Fire Lizard",
            "Age" :"987",
            "Hobbies" : "Fire Lizard: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".11",
            "NumberTwo" :"28.09",
            "NumberThree" : "33829749.00",
            "NumberFour":"379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" :"Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour":"Four Four Four Four",
            "Notes" :"Fire Lizard: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        }, {
            "Name" : "Tommy Turtle",
            "Age" :"24",
            "Hobbies" : "Tommy Turtle: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".11",
            "NumberTwo" :"28.09",
            "NumberThree" : "33829749.00",
            "NumberFour":"379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" :"Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour":"Four Four Four Four",
            "Notes" :"Tommy Turtle: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        } , {
            "Name" : "Henry Hilgard",
            "Hobbies" : "Henry Hilgard: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".11",
            "NumberTwo" :"28.09",
            "NumberThree" : "33829749.00",
            "NumberFour":"379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" :"Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour":"Four Four Four Four",
            "Notes" :"Henry Hilgard: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        }  
    ];

    angular.element(document).ready(function(){

        var tableTD = document.querySelectorAll('table td');

        // testing
        var str = "Testing the substring thingy here to see if it will work";
        document.getElementById("demo").textContent = truncate(str, 20);

        // force table content to wrap to next line after 30 characters (limit set in CSS)
        for (var i = 0; i < tableTD.length; i++){
            var text = tableTD[i].textContent;
            //var truncatedText = '';
            if(text.length > 30 ) {
                tableTD[i].classList.add('wrap');
                truncate(text, 60);
                //truncatedText = truncate(text, 60);
                //return truncatedText;

            } else { tableTD[i].classList.add('nowrap'); }

        }

        // testing
        // function truncate(str, num){
        //     var truncatedStr = '';
        //     if (str.length > num) {
        //         truncatedStr = str.slice(0, (num - 2)) + '...'
        //     }
        //     return truncatedStr;
        // };

        function truncate(str, num){
            truncateStr = str.slice(0, (num - 2)) + '...';

            return truncateStr
        }

    });

});

这是表格 HTML:

<table ng-controller="karinasSandboxCtrl">
    <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
          <th>Hobbies</th>
          <th>Number 1</th>
          <th>Number 2</th>
          <th>Number 3</th>
          <th>Number 4</th>
          <th>Content To Make Longer 1</th>
          <th>Content To Make Longer 2</th>
          <th>Content To Make Longer 3</th>
          <th>Column One</th>
          <th>Column Two</th>
          <th>Column Three</th>
          <th>Column Four</th>
          <th>Notes</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="x in records">
          <td>{{x.Name}}</td>
          <td>{{x.Age}}</td>
          <td>{{x.Hobbies}}</td>
          <td>{{x.NumberOne}}</td>
          <td>{{x.NumberTwo}}</td>
          <td>{{x.NumberThree}}</td>
          <td>{{x.NumberFour}}</td>
          <td>{{x.ContentToMakeLonger1}}</td>
          <td>{{x.ContentToMakeLonger2}}</td>
          <td>{{x.ContentToMakeLonger3}}</td>
          <td>{{x.ColumnOne}}</td>
          <td>{{x.ColumnTwo}}</td>
          <td>{{x.ColumnThree}}</td>
          <td>{{x.ColumnFour}}</td>
          <td>{{x.Notes }}</td>
       </tr>
   </tbody>
</table>

这是相关的 CSS:

td {
      padding: 6px 12px;
      vertical-align: top;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 30ch; // "ch" limits number of characters per line.
      &.nowrap {
        white-space: nowrap;
      }
      &.wrap {
        white-space: normal;
        min-width: 29ch; // so the line will not wrap before 29ch
      }
    }

我是 javascript 的新手,所以我可能在这里遗漏了一些东西。我感谢任何帮助:)

最佳答案

您实际上是在 chop 文本,但您并未在更改后将其分配给您的变量。

每当使用 JavaScript 操作字符串时,它不会改变原始字符串,而是创建一个新字符串。

这意味着当使用 splice 时,您必须重新分配您的初始变量。这可以通过改变

truncate(text, 60)

var truncatedText = truncate(text, 60)

您还需要为 td 分配新值

tableTD[i].textContent = truncatedText;

完整代码

    for (var i = 0; i < tableTD.length; i++){
        var text = tableTD[i].textContent;

        if(text.length > 30 ) {
            tableTD[i].classList.add('wrap');
            var truncatedText = truncate(text, 60);
            tableTD[i].textContent = truncatedText;
            return truncatedText;

        } else { tableTD[i].classList.add('nowrap'); }

    }

    function truncate(str, num){
        truncateStr = str.slice(0, (num - 2)) + '...';

        return truncateStr;
    }

例子:

这是一个简单的示例,显示 chop 工作正常:

chop 字符串示例

let el = document.querySelector.bind(document);

function truncate(str, num) {
  truncateStr = str.slice(0, (num - 2)) + '...';
  return truncateStr;
}


el("input").addEventListener("input", function(e) {

  const text = e.currentTarget.value,
    truncated = truncate(text, 5);

  el("output").value = truncated;

});
strong.keyword,
var.keyword {
  font-family: monospace;
  text-transform: uppercase;
  font-size: 1.2em;
}
<main>
  <input type="text" />
  <br/>
  <output name='truncated'></output>
  <br/>
  <h4>Type in the <var class="keyword">input</var> box. The <var class="keyword">output</var> will be <strong class='keyword'>truncated</strong></h4>
</main>


这是一个将字符串变量分配给 DOM 并在两个类之间切换的示例:

将 chop 的文本分配给 DOM

const el = document.querySelector.bind(document);
const Tbody = el("table tbody");

function truncate(str, num) {
  truncateStr = str.slice(0, (num - 2)) + '...';
  return truncateStr;
}


for (row of Tbody.rows) {
  for (cell of row.cells) {

    const text = cell.textContent,
    isLongText = text.length > 30,
    
    CL = cell.classList,
    order = isLongText ? "reverse" : "sort",
    classes = ["nowrap", "wrap"][order]();

    CL.replace(...classes) || CL.add(classes[0]);
    
    cell.textContent = isLongText ? truncate(text, 30) : text;
  }
}
td {
  padding: 6px 12px;
  vertical-align: top;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 30ch;
}

td.nowrap {
  border: inset 2px black;
  white-space: nowrap;
}

td.wrap {
  border: inset 2px red;
  white-space: normal;
  min-width: 29ch; 
}
<main>
  <table>
    <thead>
      <tr>
        <th>First Column</th>
        <th>Second Column</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>R1 - C1 This is a demonstration of truncation</td>
        <td>R1 - C2</td>
      </tr>
      <tr>
        <td>R2 - C1 This text will be truncated</td>
        <td>R2 - C2</td>
      </tr>
      <tr>
        <td>R3 - C1</td>
        <td>R3 - C2 I am not truncated!</td>
      </tr>
    </tbody>
  </table>
</main>

注意:我添加了彩色边框以便更容易地查看不同的类(class)作业。 红色换行blacknowrap

关于javascript - slice() 在控制台中正确返回,但字符串在 <td> 中未被替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59637157/

相关文章:

javascript - 切片/合并 blob 的渐近复杂性

javascript - 如何在 Angular 中将动态 JSON 对象数组导出为 CSV?

jquery - 计算 body 的高度

javascript - 当我们单击 ul 中的列表项时,如何将 fa-angle-left 更改为 fa-angle-down

ios - 打开 facebook 页面进入 facebook 应用 Ios + ionic

javascript - Grunt 在编辑 js 文件后应用更改

javascript - 如何在 MobX 中将可观察映射定义为类的成员

jquery - 通过 src 查找属性的值

angularjs - $ location.path不起作用

javascript - AngularJS ng-include 在指令链接中不起作用