通过 JavaScript 更改多个 HTML 表格单元格的最佳方法

在 HTML 表中,我必须更改几个列标题,例如:<th class="myclass">Headline_01</th>应该变成<th class="myclass">Nice Headline 01</th>。作为 javascript 的初学者,我可以使用以下代码实现此目的:


window.onload = function() {

    'use strict';

    document.body.innerHTML = document.body.innerHTML.replace("Headline_01","Nice Headline 01");

    document.body.innerHTML = document.body.innerHTML.replace("Headline_02","Nice Headline 02");

    document.body.innerHTML = document.body.innerHTML.replace("Headline_03","Nice Headline 03");

}

这就是我所拥有的:


<table>

  <thead>

    <tr>

      <th class="myClass1">Current unique Headline for myClass1</th>

    </tr>

    <tr>

      <th class="myClass2">Current unique Headline for myClass2</th>

    </tr>

   ....

  </thead>

这就是我需要的:


<table>

  <thead>

    <tr>

      <th class="myClass1">New unique Headline for myClass1</th>

    </tr>

    <tr>

      <th class="myClass2">New unique Headline for myClass2</th>

    </tr>

    .....

  </thead>

我必须更改 20 多个项目,并且总是重复相同的代码对我来说似乎是错误的,我认为这也会导致性能不佳。我应该如何改进我的代码?感谢您的提示!


跃然一笑
浏览 119回答 1
1回答

函数式编程

班级const changes = {&nbsp;&nbsp; "myClass1": "New unique Headline for myClass1",&nbsp;&nbsp; "myClass2": "New unique Headline for myClass2"&nbsp;};Object.keys(changes)&nbsp; .forEach(key => document.querySelectorAll("table th."+key)&nbsp; &nbsp; .forEach(th => th.textContent = changes[key]));<table>&nbsp; <thead>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <th class="myClass1">Current unique Headline for myClass1</th>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <th class="myClass2">Current unique Headline for myClass2</th>&nbsp; &nbsp; </tr>&nbsp; </thead>内容:const changes = {&nbsp; "Current unique Headline for myClass1": "New unique Headline for myClass1",&nbsp; "Current unique Headline for myClass3": "New unique Headline for myClass3"};[...document.querySelectorAll("th")].forEach(th => {&nbsp; const text = changes[th.textContent];&nbsp; if (text) th.textContent = text;});<table>&nbsp; <thead>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <th class="myClass1">Current unique Headline for myClass1</th>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <th class="myClass2">Current unique Headline for myClass2</th>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <th class="myClass3">Current unique Headline for myClass3</th>&nbsp; &nbsp; </tr>&nbsp; </thead>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript