2017-07-25 56 views
1

我可能會在這裏失去彈珠,但我覺得這是非常簡單的JavaScript。出於某種原因,#recipes元素上的第一個addEventListener調用會觸發第一個和第二個事件處理程序中的語句,而第二個事件處理程序根本不起作用。兩個不同元素上的兩個addEventListener函數

var recipes = document.getElementById('recipes'); 
var close_heart = document.getElementById('close_heart'); 
var recipes_container = document.getElementById('recipes_container'); 

recipes.addEventListener('click', function(){ 
    recipes_container.style.display = 'block'; 
}); 

close_heart.addEventListener('click', function(){ 
    recipes_container.style.display = 'none'; 
}); 

<div id="recipes"><a href="#" id="close_heart"><span>Recipes</span></a></div> 
    <section id="recipes_container"><a href="#" class="fa fa-gittip"></a> 
    <h1>Real Mac &amp; Cheese</h1> 
     <ul> 
     <li>Rule #1 &ndash; Use only real cheese (no powdered cheese ever!)</li> 
     <li>Rule #2 &ndash; Use multiple cheese-type varieties (ex: sharp cheddar, monterey jack, bleu)</li> 
     <li>Rule #3 &ndash; Choose an extra protein like bacon to liven it up!</li> 
     </ul> 
    </section> 
</div> 

謝謝。

+2

請分享html – RahulB

+0

我太尷尬了。 –

回答

2

沒有你的HTML我只能推測,但我願意打賭,你遇到的是事件冒泡。

#recipes可能封裝#close_heart使得click#close_heart意願冒泡並觸發click事件處理程序#recipes爲好。

您可以使用.stopPropagation()來解決此問題。它將防止事件冒泡DOM並觸發父元素上的事件處理程序。

recipes.addEventListener('click', function(event){ 
    event.stopPropagation(); 
    recipes_container.style.display = 'block'; 
}); 

close_heart.addEventListener('click', function(event){ 
    event.stopPropagation(); 
    recipes_container.style.display = 'none'; 
}); 

下面是與事件捕獲和事件冒泡一個有用的解釋另一個StackOverflow的問題:What is event bubbling and capturing?

編輯:現在你已經包含在您的HTML,我可以看到,確實是一個問題。

+0

這是HTML。我粗心。我應該刪除這個問題嗎? –

+0

抱歉浪費任何人的時間。 –

+1

@GraySpectrum不,這是一個非常有效的問題。事件冒泡首先是一個棘手的概念 - 甚至意識到事件冒泡存在。我建議你用'#recipes'和'#close_heart'的HTML代碼更新你的問題,以使它更加完整。 –

0

我只是錯位了一個id屬性。 close_heart id應該放置在嵌套在節中的錨元素中。

+1

您還遇到事件冒泡的問題。 '#close_heart'上的任何'click'都會觸發'#recipes'的'click'事件處理程序。我的回答顯示你如何解決這個問題。 –

+0

我明白了。因爲#close_heart元素嵌套在#recipes div中,所以默認情況下click事件會冒泡並觸發#recipes div上的事件。感謝你在此堅持。我之前就已經理解了這個概念,而且這個例子使得它更加清晰。 –

+0

非常歡迎:) –

0

也許您錯過了爲元素分配正確的ID。檢查下面的代碼,它應該適用於你的情況:

<html> 
    <head> 
     <title> The Title </title> 
    </head> 
    <body> 

     <button id="recipes"> Recipes </button> 
     <button id="close_heart"> Close_heart </button> 
     <h1 id="recipes_container"> Recipes Container </h1> 

     <script> 
      var recipes = document.getElementById('recipes'); 
      var close_heart = document.getElementById('close_heart'); 
      var recipes_container = 
      document.getElementById('recipes_container'); 

      recipes.addEventListener('click', function(){ 
       recipes_container.style.color = "blue"; 
      }); 

      close_heart.addEventListener('click', function(){ 
       recipes_container.style.color = "orange"; 
      }); 
     </script> 
    </body> 
</html> 
+0

謝謝Reza。確實是這樣,但還有另一個事件冒泡的問題,艾略特B很善於指出和解釋。 –