2017-06-02 73 views
0

我有我的上一個問題中的以下腳本。我試着運行它,但它不會工作。沒有任何控制檯消息。它與名爲lstr.js的控制檯發生衝突(我認爲它與Chrome相關),代碼在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 MENT).ready'? – ThisGuyHasTwoThumbs

+1

您將不得不向我們展示您的HTML。你甚至已經加載腳本? –

回答

0

包裹在一個函數,然後做

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(); 
} 

代碼是,除非你確定應該檢查是否links.length === contentDivs.length

+0

我收到一條錯誤,提示'無法讀取屬性'樣式'未定義' – Nofel

+0

您遺漏了一個或多個要設置的元素'.style'屬性。請提供您的HTML,以便我們可以更好地爲您提供幫助。 –

+0

[這裏](https://codepen.io/codearts/pen/ZyzNBw),抱歉花了時間重現。 – Nofel

相關問題