问题描述
我曾经为选定的 <option>
执行此操作:
var select_filter = document.getElementById("myDropdown");
if (select_filter && select_filter[select_filter.selectedindex].value == 0) {
///...
}
但是现在我在 <li>
中使用了 <ul>
元素,那么我怎样才能实现与上述相同的效果?
编辑 添加了 html:
<ul class="nav nav-tabs" id="nav-tabs">
<li class="nav-item" id="Driftcenter-nav-tav">
<a class="nav-link active" data-toggle="tab" href="#Driftcenter"
onclick="load_business_units(); showFilter();">Driftcenter</a>
</li>
<li class="nav-item" id="vognmaend-nav-tav">
<a class="nav-link" data-toggle="tab" href="#vognmaend"
onclick="load_operation_carrier_list(); showFilter();">Vognmænd</a>
</li>
<li class="nav-item" id="ads-segment-nav-tav">
<a class="nav-link" data-toggle="tab" href="#ads-segment"
onclick="load_ads_units(); showFilter();">ADS Segment</a>
</li>
<li class="nav-item" id="traffik-info-nav-tab">
<a class="nav-link" data-toggle="tab" href="#trafik-info"
onclick="filterTrafficCondition(); hideFilter();">Trafikinfo</a>
</li>
<li class="nav-item" id="vejr-varsel-nav-tab">
<a class="nav-link" data-toggle="tab" href="#vejr-varsel"
onclick="filterTrafficWeather(); hideFilter();">Vejrvarsel</a>
</li>
</ul>
解决方法
您可以执行以下示例来获取点击列表项的索引
const ulList = document.getElementById("ul-ele");
const li = document.getElementsByTagName('li');
var nodes = Array.from( ulList.children );
let selected = -1;
document.getElementById("ul-ele").addEventListener("click",function(e) {
if (selected !== nodes.indexOf(e.target)) {
selected = nodes.indexOf(e.target);
console.log(selected);
} else {
console.log("Already selected");
}
});
<html>
<body>
<ul id="ul-ele">
<li>Index 1</li>
<li>Index 2</li>
<li>Index 3</li>
<li>Index 4</li>
</ul>
</body>
</html>