javascript - 多个元素具有相同的功能

标签 javascript jquery html function

我有这个代码:

https://jsfiddle.net/eur59yfa/6/

-Html 和 JS

     <body>
<table>
<tr>
<td class="first">100</td>
<td class="second">20</td>
</tr>
</table>
    <script>
    document.body.onload = function(){
         var firstTdVal = document.getElementsByClassName('first')[0].innerHTML;
       var secondTdVal = document.getElementsByClassName('second')[0].innerHTML;
       var valueToBeShown = parseInt(firstTdVal)/parseInt(secondTdVal);
       document.getElementsByClassName('second')[0].innerHTML = valueToBeShown ;
    }
    </script>
</body>

代码运行良好,但我有一个问题。例如,会有其他 td 具有“.third”类、“.fourth”...具有不同的值:240,451...并且所有这些类都必须分为类“.second”。每个结果应显示在自己的 td 中。如何做到这一点,同时保持代码复杂性?

最佳答案

可能超出您的需要,但这展示了如何迭代数组、创建动态元素(并填充它们)以及如何动态分配类和管理新创建元素的 CSS。祝你好运。

let thead = document.querySelector('table thead tr');
let rows = document.querySelectorAll('tbody tr');
let dividends = ['first', 'third', 'fourth'];

// Dynamically Create Table Headers
dividends.forEach(x => {
  let new_th = document.createElement('th');
  
  // capitalize the class to use in the table header
  let title = x.replace(/\b([a-z])/g, (s) => {
    return s.toUpperCase()
  });
  
  // prepend "result-" to the class (e.g., "result-first")
  new_th.className = `result-${x}`;  
  new_th.appendChild(document.createTextNode(`${title} Result`));
  thead.appendChild(new_th);
});

// Dynamically Generate Result Values (and new table data cells)
Array.prototype.forEach.call(rows, function(row, index) {
  let divisor = +row.querySelector('.second').textContent;

  dividends.forEach(handle => {
    let dividend = +row.querySelector(`.${handle}`).textContent;
    let quotient = dividend / divisor;
    let new_cell = document.createElement('td');
    
    // append "-value" to the class (e.g., "first-value")
    new_cell.className = `${handle}-value`;
    new_cell.appendChild(document.createTextNode(quotient)); // add value
    row.appendChild(new_cell);
  });
});
/* superfluous table styling */
body {
  font-size: 16px;
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, "Segoe UI", "Calibri LIght", "Roboto Light", "Roboto", "Lucida Grande", Verdana, Arial, sans-serif;
  font-weight: 300;
}
table {
  border-collapse: collapse;
  border: 1px solid;
}
thead {
  border-bottom: 1px solid;
}
td {
  border-left: 1px solid;
  text-align: left;
}
td,
th {
  padding: 4px;
}
/* end page + table styling */


/* demonstrates how to grab the first part of the class name */

[class^=result-] {
  color: #09c;
}
/* demonstrates how to grab the last part of the class name */

[class$=-value] {
  color: #900;
  text-align: right;
}
<table>
  <thead>
    <tr>
      <th>First</th>
      <th>Second</th>
      <th>Third</th>
      <th>Fourth</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="first">100</td>
      <td class="second">10</td>
      <td class="third">300</td>
      <td class="fourth">400</td>
    </tr>
    <tr>
      <td class="first">1000</td>
      <td class="second">10</td>
      <td class="third">3000</td>
      <td class="fourth">4000</td>
    </tr>
  </tbody>
</table>

关于javascript - 多个元素具有相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914860/

相关文章:

javascript - 为什么 jQuery cookie 插件不将浮点变量保存为值?

jquery - css 菜单边框动画无法正常工作

javascript - 为什么 JavaScript 警报在 Phonegap Android 应用程序中显示空字符串,而代码在浏览器上运行良好?

javascript - 不支持 svg 的浏览器的 CSS hack

javascript - 如何使用 Astronomy 的父属性验证表单 - MeteorJS

javascript - 如何在具有对象的 React 应用程序中循环遍历 javascript 数组并获取具有特定值的属性的计数

javascript - JavaScript 中的插入排序算法

jquery - 如何仅从字符串中获取 HTML 标签

html - 在 HTML5 和 CSS3 中我可以自由使用什么?我应该避免哪些功能?

javascript - 动态双菜单