2016-06-24 2 views
0

私のページ上のすべてのボタンが別のページにリンクするように見える問題がある、IDまたは特定の要素を使用する例えば:。 onclickクラスまたはタグを使用して、すべてのボタンを別のページにリンクする方法

しかし、やって.onclick [0] document.getElementsByTagName( "ボタン")document.getElementsByTagName( "ボタン")のonclick(ので、すべてのボタン) またはdocument.getElementsByClassName( "theButtons")をやってonclickの。 does not work。

私のJavascriptコード:

window.onload = function(){ 
      document.getElementsByTagName("button").onclick = function() { 
      location.href = "../index.html"; 
      }; 
     }; 

<button class="theButtons">click me</button> 
<button class="theButtons">click me</button> 
<button class="theButtons">click me</button> 
+1

'getElements'関数は、反復処理が必要な配列のようなオブジェクトを返します。 – 4castle

+0

このための標準はありませんか?私は1つを見つけることができませんでした。 –

+0

@ 4castle - 配列ではありませんが、ライブHTMLCollectionです。 –

答えて

1

あなたは、ドキュメント内のボタンのコレクションをループする必要があります。 document.getElementsByTagName()は、一致するすべての要素のコレクションを返します。そのため、配列全体をループし、各項目のonClickを割り当てる必要があります。

window.onload = function(){ 
    var buttons = document.getElementsByTagName('button'); 
    for (var i = 0; i < buttons.length; i++) { 
     var button = buttons[i]; 
     button.onclick = function() { location.href = "../index.html"; }; 
    } 
} 
-1

別のオプションは、jqueryのclick()はフィドルhttp://jsfiddle.net/85qLh41a/3/

<button class="theButtons">click me</button> 
<button class="theButtons">click me</button> 
<button class="theButtons">click me</button> 
<script> 
    $(".theButtons").click(function() { 
    location.href = '../index.html'; 
    }); 
</script> 

それともこれはdocument.getElementsByTagNameが返されますので、あるページのすべてのボタンの

<script> 
    $("button").click(function() { 
    location.href = '../index.html'; 
    }); 
</script> 
1

のために動作しますを参照してください使用することですHTMLCollection、document.getElementByIdはDOM要素を返します。 HTMLCollectionはイベントリスナーを追加できません。

あなたは試すことができます:

  1. 配列は、各buttonclickイベントハンドラを登録しても使用forループが行きます。
  2. event bubblingを使用してください。 1つのイベントハンドラをコンテナに登録して、その子のすべてのイベントを待機します。 (推奨)。

希望すると便利です。

関連する問題