![](/img/trans.png)
[英]How do I get the last element child for every item in an array and then show them if they are clicked on
[英]How do I get the last element child for every item in an array
所以我需要做的是抓住數組中每個項目的最后一個元素子元素。
function myDropdown() {
var x = document.getElementsByClassName('sub-menu-wrap')[0].lastElementChild
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
我知道這有效:
document.getElementsByClassName('sub-menu-wrap')[0].lastElementChild
但是我沒有定義數組中我希望它使用哪個項目,而是需要它來動態獲取數組中的每個項目並為它們獲取.lastElementChild
。
只是為了添加這個,我需要這個函數作為onclick工作,只有在點擊它們時才會應用於任何項目
希望有人可以幫忙!
var arr = Array.from(document.getElementsByClassName('sub-menu-wrap'));
for (let el of arr) {
var x = el.lastElementChild;
/// do what you want to x here
}
實際上我認為你不需要將它轉換為帶有Array.from的數組,如果你正在做for..of..
,但如果你正在做arr.forEach()
你會
試試這樣吧。 獲取類sub-menu-wrap
的數組並將其循環並隱藏/顯示您的最后一個子元素
function myDropdown() { var array = Array.from(document.getElementsByClassName('sub-menu-wrap')); for (let data of array) { var x = data.lastElementChild; if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } } myDropdown()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="sub-menu-wrap"> <div>hi1</div> <div>hi2</div> <div>hi3</div> </div> <div class="sub-menu-wrap"> <div>hi1</div> <div>hi2</div> <div style="display:none">hi3</div> </div>
如果要隱藏最后一個孩子的被點擊元素
function hideLast(e) { var x = e.lastElementChild; if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="sub-menu-wrap" onclick="hideLast(this)"> <div>hi1</div> <div>hi2</div> <div>hi3</div> </div> <div class="sub-menu-wrap" onclick="hideLast(this)"> <div>hi1</div> <div>hi2</div> <div style="display:none">hi3</div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.