gpt4 book ai didi

javascript - 如何检查表中的所有 是否同时为空?

转载 作者:行者123 更新时间:2023-11-28 12:12:04 24 4
gpt4 key购买 nike

我有一张 table ,里面有 3 <tr>和 3 <td>每一个里面。

td 是动态填充的,在某些时候我想检查表中的所有 td 是否同时为空,如果是则返回 true。

我尝试使用.each()但我没能成功。

谢谢!

这是我的 HTML 用于澄清:

<table id="board">
<tr>
<td id="spot1" class="spot"></td>
<td id="spot2" class="spot"></td>
<td id="spot3" class="spot"></td>
</tr>
<tr>
<td id="spot4" class="spot"></td>
<td id="spot5" class="spot"></td>
<td id="spot6" class="spot"></td>
</tr>
<tr>
<td id="spot7" class="spot"></td>
<td id="spot8" class="spot"></td>
<td id="spot9" class="spot"></td>
</tr>
</table>

最佳答案

我建议使用原生 JavaScript:

// using Arrow syntax to create a named function, into
// which we pass a CSS selector:
const areAllEmpty = (selector) => {

// we use Array.from() to convert the iterable result of
// document.querySelectorAll() into an Array, and then
// use Array.prototype.every() to iterate over the Array
// elements:
return Array.from(document.querySelectorAll(selector)).every(
// again, using an Arrow function expression, 'cell'
// is the user-defined variable name referring to the current
// element of the Array of elements over which we're iterating;
// here we test that the textContent, when leading/trailing
// white-space is removed, of the current element is exactly
// equal to an empty string:
(cell) => cell.textContent.trim() === ''

// if this assessment returns true every element in the Array
// Array.prototype.every() returns true; otherwise it will
// return false.
);
}

const areAllEmpty = (selector) => {
return Array.from(document.querySelectorAll(selector)).every(
(cell) => cell.textContent.trim() === ''
);
}

console.log(areAllEmpty('#board td'));
<table id="board">
<tr>
<td id="spot1" class="spot"></td>
<td id="spot2" class="spot"></td>
<td id="spot3" class="spot"></td>
</tr>
<tr>
<td id="spot4" class="spot" </td>
<td id="spot5" class="spot"></td>
<td id="spot6" class="spot"></td>
</tr>
<tr>
<td id="spot7" class="spot"></td>
<td id="spot8" class="spot"></td>
<td id="spot9" class="spot"></td>
</tr>
</table>

引用文献:

关于javascript - 如何检查表中的所有 <td> 是否同时为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59847778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com