2017-06-21 42 views
0

我有一個菜單按鈕,多次出現在我點擊事件的網站上。點擊同一個類的多個實例不工作

當我點擊按鈕時什麼都沒有發生(當只有一個按鈕的實例工作正常)。我知道我需要循環遍歷一個類的多個實例創建的節點列表,但是當我現在單擊該按鈕時,什麼也沒有發生,並且我沒有在控制檯中得到任何錯誤信息給我任何指針?

下面是Javascript和一個簡易的插圖。

Codepen:https://codepen.io/emilychews/pen/owWVGz

JS

var $mainMenuButton = document.getElementsByClassName('desktopmenubutton'); 
var $mainMenuButtonAll = function() { 
    for(h = 0; h < $mainMenuButton.length; h+=1) { 
     $mainMenuButton[i]; 
    } 
}; 

$mainMenuButtonAll.onclick = function() { 

    $mainMenuButtonAll.style.background = "black"; 

}; 

任何幫助將是真棒。

艾米莉

+0

你的循環實際上並沒有做任何事情,你的函數也不會返回任何東西。這是一個固定版本:https://codepen.io/anon/pen/MomRgY?editors=0010 –

回答

1

我編輯的代碼你,檢查意見和jsFiddle

// get all the buttons with this tag name (or use class name) 
var allButtons = document.getElementsByTagName('desktopmenubutton'); 

// add a click listener to each button 
for(h = 0; h < allButtons.length; h+=1) { 
    allButtons[h].addEventListener("click", function(e){ 
     console.log("yo yo"); 
      e.currentTarget.style.backgroundColor = "black"; 
    }) 
} 
1

var $el = document.getElementsByClassName('desktopmenubutton');

// Solution 1 
for (var i = 0; i < $el.length; i++) { 
    // If on clicking any element, only that should change 
    $el[i].onclick = function() { 
     this.style.background = 'black'; 
    } 
} 

// Solution 2 
for (var i = 0; i < $el.length; i++) { 
    // If on clicking any element, all should change 
    $el[i].onclick = function() { 
     for (var j = 0; j < $el.length; j++) { 
      $el[j].style.background = 'black' 
     } 
    } 
} 

首先,我們得到的所有元素,並結合獨立的點擊處理程序seperately的所有元素。解決方案1當您想要更改所有元素時,只需更改點擊元素和解決方案2。

1
var $mainMenuButton = document.getElementsByClassName('desktopmenubutton'); 

var $mainMenuButtonAll = function() { 
    for(h = 0; h < $mainMenuButton.length; h+=1) { 
     $mainMenuButton[h].addEventListener("click", function(){ 
     this.style.background = 'black'; 
     }); 
    } 
}; 


$mainMenuButtonAll(); 

您需要將按鈕的每次出現與事件點擊進行綁定以對其執行某些操作。

1
var $mainMenuButton = document.getElementsByClassName('desktopmenubutton'); 
for(var h = 0; h < $mainMenuButton.length; h++) { 
    $mainMenuButton[h].addEventListener('click', function() { 
     this.style.background = "black"; 
    }); 
} 

這是一個工作示例。

我做了什麼:

  1. 刪除了$mainMenuButtonAll變量,因爲沒有需要它。

  2. 作出h變量在for循環的地方,而不是全局(更多的here

  3. 添加事件偵聽器以每$mainMenuButton,因爲它從來沒有很好覆蓋onclick事件。

相關問題