2017-06-18 28 views
0

檢測類的名稱很簡單。如何檢測類元素的有序位置

event.target.className

然而如果檢測一個給定的元件是使用特定的類是艱難的,至少對我的第三,第五或第11位。我使用控制檯(F12)來查找我可以使用但沒有運氣的屬性。

在以下簡化示例中,哪些屬性或其他功能可以確定用戶是否單擊了("box-a")[0]("box-a")[1]("box-a")[2]("box-a")[3]?我知道我可以爲每個元素使用單獨的ID,但如果技術上可行,我寧願保持簡單。

var count; 
 
\t 
 
for (count = 0; count < 4; count++) { 
 
    document.getElementsByClassName("box-a")[count].addEventListener("click", checker); 
 
} 
 

 
function checker() { 
 
    document.getElementsByClassName("box-b")[0].innerHTML = event.target.className; 
 
} 
 

 
// event.target.className targets the classes name, but what property targets the [0], [1], [2] or [3]?
.box-a { 
 
    background-color: green; 
 
    border: 0.6rem solid black; 
 
    padding: 10px; 
 
    font-family: arial; 
 
    font-size: 4rem; 
 
} 
 

 
.box-b { 
 
    display: block; 
 
    background-color: blue; 
 
    border: .25rem solid red; 
 
    padding: 10px; 
 
    font-family: arial; 
 
    font-size: 4rem; 
 
}
<div class="box-a">Box 1</div> 
 
<div class="box-a">Box 2</div> 
 
<div class="box-a">Box 3</div> 
 
<div class="box-a">Box 4</div> 
 
<div class="box-b"></div>

+0

你有什麼計劃一旦你得到它與索引呢? – 2017-06-18 02:40:23

回答

0

當在元素上循環,添加一個事件偵聽器以傳遞點擊框的索引你的checker功能每箱。

function checker(index) { 
 
    // Do whatever you want with the index here 
 
    console.log(index) 
 
} 
 

 
// Add the same event listener to each element, but passing the index of 
 
// the element to the checker function 
 
[].slice.call(document.getElementsByClassName('box-a')) 
 
    .forEach(function(element, index) { 
 
     element.addEventListener('click', function() { checker(index) }) 
 
    })
<div class="box-a">Box 1</div> 
 
<div class="box-a">Box 2</div> 
 
<div class="box-a">Box 3</div> 
 
<div class="box-a">Box 4</div> 
 
<div class="box-a">Box 5</div>

+0

這個答案的問題是索引將被硬編碼,假設你刪除第三個元素,「Box 4」將仍然有索引3. – Gerardo

+0

@Gerardo好的,你沒有提到這一點。解決方法:當添加/刪除框時,分離所有事件偵聽器並重新添加? – Anko

+1

我沒有提到,因爲我不是那個問這個問題的人。我只是認爲他可能想要添加/刪除元素,這個答案只有在元素被添加或刪除之前纔會起作用。關於附加/分離聽衆肯定會工作,但這不是一個好習慣。 – Gerardo

0

這可能不是最好的解決方案,但它的工作原理。

// Click on any div element and see the output 

document.querySelectorAll('.box-a').forEach((e) => { // Add the event listener to all the elements with class .box-a 
    e.addEventListener('click', (event) => { 
    var element = event.target; 
    var index = Array.from(element 
     .parentNode // Get the parent node of the clicked element 
     .querySelectorAll('.' + element.className)) // Select all the elements inside the parent node (siblings) with the same class name of the clicked element 
     .indexOf(element) + 1; // Look for the index of the clicked element, + 1 
    console.log(index); 
    }); 
}); 

這裏有一個工作斌:

JSBin