簡體   English   中英

JavaScript 在 ul 中查找 li 索引

[英]JavaScript find li index within ul

我試圖在 Javascript 中通過 id 找到我的列表項的索引。 例如,我有 5 個項目的列表,並給出了一個元素,我想弄清楚它在列表中的哪個位置。 下面是我希望構建的代碼。

它使用 onclick 處理程序來查找正在工作的元素,然后我只需要以某種方式找出元素在列表“squareList”中的位置。

window.onload=function(){
    function getEventTarget(e){
        var e=e || window.event;
        return e.target || e.srcElement;
    }

    function selectFunction(e){
        var target=getEventTarget(e);
        alert(target.id);
    }

    var squareList=document.getElementById('squareList');
    squareList.onclick=function(e){
        selectFunction(e);
    }
}

要獲取索引,您可以執行以下操作:

Array.prototype.indexOf.call(squareList.childNodes, target)

使用 jQuery,因為您已經在使用跨瀏覽器的解決方法:

$(document).ready(function() {
    $('#squareList li').click(function() {
        var index = $(this).index();
    })
});

我有另一個解決方案,想分享

function getEventTarget(e) {
  e = e || window.event;
  return e.target || e.srcElement; 
}

let ul = document.getElementById('squareList');
ul.onclick = function(event) {
  let target = getEventTarget(event);
  let li = target.closest('li'); // get reference by using closest
  let nodes = Array.from( li.closest('ul').children ); // get array
  let index = nodes.indexOf( li ); 
  alert(index);
};

你可以在這里驗證

參考: 最近

使用 es6 和 findIndex

將 ul 節點列表轉換為數組: [...UL_ELEMENT.children]然后使用findIndex檢查您要查找的元素。

const index = [...UL_ELEMENT.childNodes].findIndex(item => item === LI_ELEMENT)

使用擴展運算符 [...] 將 ul 元素的子元素轉換為數組,然后使用 Array.prototype.indexOf() 方法將子元素作為參數傳遞。

const index = [...UL_ELEMENT.children].indexOf(LI_ELEMENT);

您可以在列表或數組中獲取所有“li”,然后使用簡單的循環搜索位置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM