2017-07-27 36 views
0

我想编写一个程序,它将返回父元素内的子元素位置,但是我遇到了问题。我试着编写下面的代码,但没有按预期工作;不是返回位置值,而是返回click事件。这是我想这样做:
(PS我想解决原料JS这个问题)在点击事件后获取子元素的位置

(function() { 
    // body... 

     var x = document.getElementsByClassName("bubble"); 

     for(var i=0; i<x.length; i++) { 

      x[i].addEventListener('click', function(i){ 


       console.log(i); 


      }); 



     } 

})(); 

HTML:

<div id=holder> 
<div class="bubble"></div> 
<div class="bubble"></div> 
<div class="bubble"></div> 
<div class="bubble"></div> 
</div> 
+0

您正在描述jQuery中indexOf的功能:https://api.jquery.com/index/ – ControlAltDel

+0

'console.log(i.clientX,i.clientY)'? –

+0

@ControlAltDel没有'jQuery'标记。 –

回答

1

,你可以请执行以下操作:

  1. 确保父DIV(#holder)位于
  2. 利用offsetLeftoffsetTop

如果你想找到在阵列位置的位置,你可以使用

Array.prototype.indexOf.call(collection, element)

(function() { 
 
    // body... 
 
    var x = document.getElementsByClassName("bubble"); 
 

 
    for (var i = 0; i < x.length; i++) { 
 

 
    x[i].addEventListener('click', function(a) { // change the variable name here otherwise you have a local var i conflicting with the loop var i 
 

 
     console.log(this.offsetLeft, this.offsetTop); // this is the element clicked 
 
     
 
     console.log(Array.prototype.indexOf.call(x, this) + 1); // this is the position as an index (plus 1) 
 
    }); 
 
    } 
 

 
})();
#holder { 
 
    position:relative; /* position the parent */ 
 
}
<div id="holder"> 
 
    <div class="bubble">1</div> 
 
    <div class="bubble">2</div> 
 
    <div class="bubble">3</div> 
 
    <div class="bubble">4</div> 
 
</div>

+0

检索我认为OP应该指定他想要什么。 –

+0

@Pete感谢您的尝试,但这不是我所期待的。我想要孩子在父元素内的位置。 –

+0

@TribikramAdhikari请参阅编辑 – Pete

1

i在听者的功能代表了整个元素及其事件,而不是来自for循环的index。记录它可能会导致浏览器崩溃。我建议你使用ES6宝藏Array#forEach

const elems = document.querySelectorAll('#holder .bubble'); 
 

 
Array.from(elems).forEach((v, i) => v.addEventListener('click',() => { 
 
    console.log(`Child position: ${i}`); 
 
}));
<div id="holder"> 
 
    <div class="bubble">a</div> 
 
    <div class="bubble">b</div> 
 
    <div class="bubble">c</div> 
 
    <div class="bubble">d</div> 
 
</div>

然而,如果你真的想用for循环,不传递任何参数到你的听众的功能,改变var i您的循环中为let i

const x = document.getElementsByClassName("bubble"); 
 

 
for (let i = 0; i < x.length; i++) { 
 
    x[i].addEventListener('click', function() { 
 
    console.log(i); 
 
    }); 
 
}
<div id="holder"> 
 
    <div class="bubble">a</div> 
 
    <div class="bubble">b</div> 
 
    <div class="bubble">c</div> 
 
    <div class="bubble">d</div> 
 
</div>