2017-02-11 49 views
-1

当我输入这段代码时,它不是同时运行其中一个,而是哪个先运行。外部文件中的javascript代码

var topBox = document.getElementById('boxOne'); 
topBox.textContent = 'hello!' 

var bottomSection = document.getElementById('bottomSection'); 
bottomSection.onmouseover = function() { 
    bottomSection.textContent = ''; 
    bottomSection.style.padding = ''; 
}; 

bottomSection.onmouseout = function() { 
    bottomSection.textContent = ''; 
    bottomSection.style.padding = ''; 
}; 
+1

您在输入呢?它与“外部文件”有什么关系? – UnholySheep

+1

这两个函数都做同样的事情,你怎么知道哪一个运行,哪一个不是? – JJJ

+0

我从头开始建立一个网站,并在崇高的编辑器中有HTML加JavaScript和CSS页面。如果我首先有'box0ne'代码,它只是改变这个元素。那么如果我将其更改为'bottomSection'代码,那么这个代码就可以工作,而另一个则不会,就好像它停止并且不会运行其他代码一样?很奇怪。 – Stuart

回答

0

(function(){ 
 
    var topBox = document.getElementById('boxOne'); 
 
    topBox.textContent = 'hello!' 
 

 
    var bottomSection = document.getElementById('bottomSection'); 
 
    bottomSection.onmouseover = function() { 
 
    bottomSection.textContent = 'foo'; 
 
    bottomSection.style.padding = ''; 
 
    }; 
 

 
    bottomSection.onmouseout = function() { 
 
    bottomSection.textContent = 'bar'; 
 
    bottomSection.style.padding = ''; 
 
    }; 
 
}())
<div id="boxOne"></div> 
 
<div id="bottomSection">I am bottom section</div>

看来工作。不知道什么不适合你。

+0

也许是崇高的编辑搞乱了。 – Stuart

0

你可能会希望添加事件侦听器来侦听像这样的鼠标悬停/鼠标移开操作:

var bottomSection = document.getElementById("bottomSection"); 

bottomSection.addEventListener("mouseover", function() { 
bottomSection.textContent = ''; 
bottomSection.style.padding = ''; 
}); 
+0

我必须将两段代码放在单独的文件中才能让它们在同一个网站上工作。 – Stuart

+0

在这种情况下,您可以在JS文件中分别定义函数,并将'onmouseover/onmouseout'附加到html元素。例如,你可以有: '函数mouseOverAction(){ /**鼠标上执行一些动作了*/ }' 然后在你的HTML元素,你只需要添加的鼠标动作,像这样: ''

bottom section
好 – Ethan

+0

谢谢Ethan,谢谢大家的帮助。 – Stuart