gpt4 book ai didi

javascript - 遍历 div 数组以确定每个元素是否都有子元素

转载 作者:太空宇宙 更新时间:2023-11-04 16:03:28 26 4
gpt4 key购买 nike

我正在遍历一个 div 数组,我需要检查该数组的每个 元素是否都有一个子元素。

运行下面的代码将对每个元素进行 console.log,但是我只想 console.log“一个 child 存在!”条件是 tilesArray 中的每个图 block 都有一个子元素。如何实现?

    function hasTile(tilesArray){
for(var i = 0; i < tilesArray.length; i++){
console.log(tilesArray[t]);
if(tilesArray[i].firstChild){
console.log("A child exists!");
}else{
console.log("No child.");
}
}
}

index.html

        <div class="container" id="tileContainer">
<!-- id listed by row-column notation. -->
<div class="row">
<div class="col-xs-6 col-md-12 tile" id="r1c1" onclick="main(this)"></div>
<div class="col-xs-6 col-md-12 tile" id="r1c2" onclick="main(this)"></div>
<div class="col-xs-6 col-md-12 tile" id="r1c3" onclick="main(this)"></div>
</div>

<div class="row">
<div class="col-xs-6 col-md-12 tile" id="r2c1" onclick="main(this)"></div>
<div class="col-xs-6 col-md-12 tile" id="r2c2" onclick="main(this)"></div>
<div class="col-xs-6 col-md-12 tile" id="r2c3" onclick="main(this)"></div>
</div>

<div class="row">
<div class="col-xs-6 col-md-12 tile" id="r3c1" onclick="main(this)"></div>
<div class="col-xs-6 col-md-12 tile" id="r3c2" onclick="main(this)"></div>
<div class="col-xs-6 col-md-12 tile" id="r3c3" onclick="main(this)"></div>
</div>
</div>
<!-- End of tile container -->

<div class="container" id="turnDisplayContainer">
<div class="row">
<div class="col-xs-9 col-md-6 content" id="userTurnDisplay">
<h4>Your Turn</h4>
</div>
<div class="col-xs-9 col-md-6 content" id="computerTurnDisplay">
<h5>Computer's Turn</h5>
<iframe src="assets/media/loading-wheel.gif" width="50" height="50" scrolling="no" frameBorder="0"></iframe>
</div>
</div>
</div>
<!-- <div class="container" id="timerDisplayContainer">
<div class="row">
<div class="col-xs-18 col-md-12 content" id="timerDisplay">
<h5>Timer</h5>
</div>
</div>
</div> -->
<div class="container btnContainer">
<div class="row">
<button type="button" class="btn btn-danger" id="resetButton">Reset</button>
</div>
</div>

<img class="img img-responsive gameIcon" src="assets/img/green-ring.png" alt="Green Ring Icon" id="userIcon" />
<img class="img img-responsive gameIcon" src="assets/img/red-x.png" alt="Red X Icon" id="computerIcon" />

最佳答案

您应该将附加信息存储在局部变量中。示例:

function hasTile(tilesArray){
var bAllHaveChild = tilesArray.length > 0;
for(var i = 0; i < tilesArray.length; i++){
console.log(tilesArray[t]);
if(!tilesArray[i].firstChild){
bAllHaveChild=false;
}
}
if(bAllHaveChild)
console.log("A child exists!");
else
console.log("No child.");
}

希望对你有所帮助。再见

关于javascript - 遍历 div 数组以确定每个元素是否都有子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40036591/

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