通过javascript中的元素索引访问eventListener中的元素

时间:2016-03-29 15:06:51

标签: javascript element event-listener

我想为.author_show类添加EventListener来更改.author 样式......这是我的代码

<div class="post>
    <div class="post-cont>
        // Some text
        <div class="author_show"></div>
        <div class="author_show"></div>
        // Some text
    </div>
</div>
<div class="authors">
    <div class="author"></div>
    <div class="author"></div>
</div>
<script type="text/javascript">
var author_show = document.getElementsByClassName("author_show");
var authors = document.getElementsByClassName("author");
for(var i=0;i<authors.length;i++)
{
    author_show[i].addEventListener("mouseover",function(){
        authors[i].style.display = "block"; // Problem
    })
}
</script>

...谢谢

2 个答案:

答案 0 :(得分:1)

尝试每次迭代创建scope

for(var i=0; i<authors.length; i++) {
   (function(i) {
      author_show[i].addEventListener("mouseover",function(){
        authors[i].style.display = "block"; // Problem
      }); 
    })(i);
}

在您的代码中,addEventListener不会导致任何问题。但样式设置块将依赖属于单个范围的i。至于循环迭代,i将递增,i的最终值将反映在所有事件中。所以你必须为每次迭代创建一个范围。

答案 1 :(得分:0)

这就是你想要的:

var author_show = document.getElementsByClassName("author_show");
var authors = document.getElementsByClassName("author");

for(var i=0;i<authors.length;i++) {
    (function(i) {
        var author = author_show[i];
        var style = authors[i].style;
        author.addEventListener("mouseover", function(){
            style.display = "block"; // Problem
        });
        author.addEventListener("mouseout", function(){
            style.display = "none"; // Problem
        });
    })(i);
}
.author {
   display : none;
}
<div class="post">
    <div class="post-cont">
        // Some text
        <div class="author_show">Show A</div>
        <div class="author_show">Show B</div>
        // Some text
    </div>
</div>
<div class="authors">
    <div class="author">Author A</div>
    <div class="author">Author B</div>
</div>

(另见this Fiddle