2017-04-08 10 views
0

onclick関数を3つの要素の配列に適用しようとしていますが、配列のonclickプロパティを設定しても機能しません。どんなアイデアも本当に役に立ちます。 ありがとう!ここでonclick関数を使用して配列にアクセスしよう

は私のコードです:

var btnArray = [ 
document.getElementById('buttonOne'), 
document.getElementById('buttonTwo'), 
document.getElementById('buttonThree'), 
]; 
console.log(btnArray); 
btnArray.onclick = function revilImg() { 
console.log('hey'); 
} 

答えて

2

配列にはonclickプロパティがありません。あなたは(私はArray#forEachを使用することを選択した)最初、その上反復する必要があり、addEventListenerを使用して、個別に各DOM要素にハンドラをアタッチ:

var buttons = [ 
 
    'buttonOne', 
 
    'buttonTwo', 
 
    'buttonThree' 
 
].map(document.getElementById, document) 
 

 
console.log(buttons) 
 

 
function revealImage() { 
 
    console.log('hey') 
 
} 
 

 
buttons.forEach(function (e) { 
 
    e.addEventListener('click', revealImage) 
 
})
<button id="buttonOne">#1</button> 
 
<button id="buttonTwo">#2</button> 
 
<button id="buttonThree">#3</button>

+1

あなたが見つける、または知っていました、 'document.getElementById'をマップ関数に渡すとき、それは_thisArg_として' document'を必要としますか? – LGSon

+1

@LGSon 'document'は' Document'の単なるインスタンスです。 'getElementById'は' document'の独自のプロパティではなく 'Document.prototype'で定義されています。 'document.hasOwnProperty( 'getElementById')'を実行すると、 'false'と表示されます。 – gyre

+0

ああ、ありがとう...プラス1その:) – LGSon

1

は、配列を、このようなイベントリスナー、あなたのループを追加し、ボタンが共有している場合、各オブジェクト

var btnArray = [ 
    document.getElementById('buttonOne'), 
    document.getElementById('buttonTwo'), 
    document.getElementById('buttonThree'), 
]; 

console.log(btnArray); 

for (var i = 0; i < btnArray.length; i++){ 
    btnArray[i].addEventListener('click', function(){ 
    console.log('hey'); 
    }) 
} 

にハンドラを追加します共通のクラス、つまりmybuttonsを使用できます。querySelecorAll()

var btnArray = document.querySelectorAll('.mybuttons'); 

console.log(btnArray); 

for (var i = 0; i < btnArray.length; i++){ 
    btnArray[i].addEventListener('click', function(){ 
    console.log('hey'); 
    }) 
} 
関連する問題