[英]Can't find the index number of an htmlCollection that has a particular class
我正在嘗試制作“進度”動態面包屑,在當前頁面前后具有不同的樣式。 所以我從一個引導列表組開始,我使用一些 exra php 使“活動”類動態化,具體取決於哪個頁面作為服務器端加載,包括:
<ul class="list-group list-group-horizontal d-flex justify-content-center mt-5">
<li class="bread list-group-item.active"><a href="about.php">About</a></li>
<li class="bread list-group-item"><a href="contact.php">Contact</a></li>
<ul>
然后我做了...
var myHtmlCollection = document.getElementsByClassName('bread');
console.log(myHtmlCollection);
給...
HTMLCollection(2) [li.bread.list-group-item.active, li.bread.list-group-item]
... 所以這是一個 HTMLCollection (因為我讀到當某些事情發生變化時,這些是由 DOM 更新的,而當“活動”類發生變化時,NodeList 不會改變。
然后我決定我需要知道當前頁面的索引號,所以我決定將 HTMLCollection 轉換為數組:
var myArray = Array.from(myHtmlCollection);
console.log(myArray);
給...
(2) [li.list-group-item.active, li.list-group-item.]
現在我主要關注使用內置的 findIndex() 函數。 所以這段代碼...
myArray.findIndex(myFunction);
function myFunction(i){
console.log(i);
}
這給了我以下內容
現在我很難過。 這是錯誤的方法嗎? 我試圖做一些模式匹配,但沒有任何效果。 請幫忙!
此代碼從我的 HTMLCollection 返回索引位置。
所以想象一下這些是面包屑......
<ul class="list-group list-group-horizontal d-flex justify-content-center mt-5">
<li class="bread list-group-item"><a href="contact.php">Contact</a></li>
<li class="bread list-group-item"><a href="about.php">About</a></li>
<li class="bread list-group-item.active"><a href="shop.php">Shop</a></li>
</ul>
<script>
var myHtmlCollection = document.getElementsByClassName('bread');
// loop through the HTMLCollection and push each value into an empty array which we'll call 'list'...
var list = [];
for (var i = 0; i < myHtmlCollection.length; i++) {
list.push(myHtmlCollection[i].className)
}
console.log(list.indexOf("bread list-group-item active")); // e.g. 2
</script>
當“活動”類通過某些 PHP 動態更改為不同的面包屑時,索引號也會動態更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.