2016-03-29 13 views
3

Ich möchte Eventlistener für .author_show Klasse hinzuzufügen .author Arten zu ändern ... das ist mein CodeAccess-Element in eventlistener von Element-Index in Javascript

<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> 

Dank ...

Antwort

1

Try eine scope pro Iteration,

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

In Ihrem Code erstellen die addEventListener wird keine Probleme verursachen. Der Stil-Einstellungsblock wird jedoch auf einem i basieren, der zu einem einzelnen Bereich gehört. Bei der Schleife wird iteriert, dass i inkrementiert wird und der endgültige Wert i in allen Ereignissen widergespiegelt wird. Sie müssen also einen Bereich pro Iteration erstellen.

0

Dies ist, was Sie gehen:

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>

(siehe auch this Fiddle)

Verwandte Themen