2017-02-11 45 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