function highlightRows() { const tabletr = document.querySelectorAll('myRequestTable tbody tr') if (tabletr instanceof NodeList && tabletr.length > 0) { // 类型检查 for (let i = 0; i < tabletr.length; i++) { const stepName = tabletr[i].querySelectorAll('td')[10].innerText === undefined ? '' : tabletr[i].querySelectorAll('td')[10].innerText if ((event.searchInfo.ViewType === 'InProcess' && (stepName === 'In Clarification' || stepName === 'Supplement Event Details')) || (event.searchInfo.ViewType === 'All' && (stepName === 'In Clarification' || stepName === 'Supplement Event Details'))) { tabletr[i].style.backgroundColor = 'yellow' } else { tabletr[i].style.backgroundColor = '' } } } } 优化代码
时间: 2023-10-23 19:12:45 浏览: 91
可以优化的地方有:
1. 使用 const 替换 let 来声明 tabletr 变量,因为它在函数中不会被修改。
2. 使用 for...of 循环代替 for 循环,避免手动进行索引计数。
3. 将重复的条件判断提取出来,避免重复代码。
4. 使用三元运算符来简化 if...else 语句。
优化后的代码如下:
```javascript
function highlightRows() {
const tabletr = document.querySelectorAll('myRequestTable tbody tr');
if (tabletr instanceof NodeList && tabletr.length > 0) {
for (const row of tabletr) {
const stepName = row.querySelectorAll('td')[10].innerText || '';
const isClarification = stepName === 'In Clarification' || stepName === 'Supplement Event Details';
row.style.backgroundColor = event.searchInfo.ViewType === 'InProcess' && isClarification ||
event.searchInfo.ViewType === 'All' && isClarification
? 'yellow' : '';
}
}
}
```
阅读全文