2017-06-02 75 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

相关问题