2017-06-02 18 views
0

私は以前の質問から以下のスクリプトを持っています。私はそれを実行しようとしたが動作しません。コンソールメッセージもありません。 lstr.jsというコンソールの何か(私はそれがクロムに​​関係すると思います)と衝突します。コードはjsfiddleで正常に動作しますが、私のマシンではうまく動作しません。JavaScriptコードはマシン上で実行されませんが、JSFiddleでは実行されません。

var links = document.getElementsByClassName('link'),   // add a class to the links and get them all 
    contentDivs = document.getElementsByClassName('content'); // same with the content blocks 

    for (i = 0; i < links.length; i++) {      // loop through the links to add the event listeners 
     var link = links[i]; 

     // add event listener 
     link.addEventListener('click', function(event) { 

     // reset color and hide content: 
     for (a = 0; a < links.length; a++) { 
      // number of links should match number of content 
      links[a].style.backgroundColor = 'magenta'; 
      contentDivs[a].style.display = 'none'; 
     } 

     // set colour of clicked 
     event.target.style.backgroundColor = 'grey'; 

     // show clicked content 
     document.getElementById(event.target.getAttribute("href").substring(1)).style.display = 'block'; 
     }) 
    } 
+0

'window.onload = function(){...あなたのコードはここに...}' – robertklep

+1

は '$(docuメンズ).ready'? – ThisGuyHasTwoThumbs

+1

あなたのHTMLも表示しなければなりません。スクリプトをロードしたことがありますか? –

答えて

0

あなたはlinks.length === contentDivs.lengthかどうかを確認するべき以外の機能で、その後

document.addEventListener('DOMContentLoaded', function() { 
    nameOfYourFunction(); 
}); 

だから最後に、あなたが

function attachEvents() { 
    var links = document.getElementsByClassName('link'); // add a class to the links and get them all 
    var contentDivs = document.getElementsByClassName('content'); // same with the content blocks 

    for (i = 0; i < links.length; i++) { // loop through the links to add the event listeners 
     var link = links[i]; 

     // add event listener 
     link.addEventListener('click', function(event) { 

     // reset color and hide content: 
     for (a = 0; a < links.length; a++) { 
      // number of links should match number of content 
      links[a].style.backgroundColor = 'magenta'; 
      contentDivs[a].style.display = 'none'; 
     } 

     // set colour of clicked 
     event.target.style.backgroundColor = 'grey'; 

     // show clicked content 
     document.getElementById(event.target.getAttribute("href").substring(1)).style.display = 'block'; 
     }); 
    } 
} 

document.addEventListener('DOMContentLoaded', function() { 
    attachEvents(); 
} 

のようになります可能性があり、コードがOKであるかということラップ

+0

「プロパティーのスタイルが未定義です」というエラーが表示されます – Nofel

+0

設定している要素の1つ以上が欠落しています'.style'プロパティです。あなたのHTMLも提供してください。私たちはより良いお手伝いをすることができます。 –

+0

[ここ](https://codepen.io/codearts/pen/ZyzNBw)、申し訳ありませんが再現する時間がかかりました。 – Nofel

関連する問題