2016-06-19 54 views
0

我在製作網站時遇到了很大麻煩。出於某種原因,無論我做什麼,我都無法獲得JavaScript。有什麼我錯過'啓用'這個?Javascript並不在我的網站工作

例如,我完全抄襲了一件非常簡單的事情。 https://codepen.io/thetallweeks/pen/boinE

在測試文件是這樣的:

<html> 
<head> 
<script> 
$("#button").click(function() { 
    $('.transform').toggleClass('transform-active'); 
}); 
</script> 

<style> 
.box { 
    background-color: #218D9B; 
    height: 100px; 
    width: 100px; 
} 

.transform { 
    -webkit-transition: all 2s ease; 
    -moz-transition: all 2s ease; 
    -o-transition: all 2s ease; 
    -ms-transition: all 2s ease; 
    transition: all 2s ease; 
} 

.transform-active { 
    background-color: #45CEE0; 
    height: 200px; 
    width: 200px; 
} 


</style> 
</head> 

<body> 
<div class="box transform"> 
</div> 

<input type="button" id="button" value="Click Me"></input> 
</body> 


</html> 

然而,按鈕不做任何事情在我的測試文件。 我做錯了什麼?

+0

那是因爲你jQuery缺失 –

+1

'$()'不是通用JavaScript,它是jQuery。你安裝了jQuery庫包嗎? – Claies

回答

0

除了確保JQuery的已經被加載,你也應該在結束標記之前加載jQuery代碼(script標籤),或在文件中把它包準備好函數調用。如果JQuery的已經加載又是什麼情況是,jQuery是html元素之前,你要附加已實際加載的事件被執行。所以基本上,JQuery事件看不到你的按鈕元素。

$(document).ready(function(){ 

    $("#button").click(function() { 
    $('.transform').toggleClass('transform-active'); 
}); 


}); 
+0

我不是很瞭解它,但這似乎已經完成了這個伎倆,它現在正在工作。 所以每次我使用JavaScript在我的地盤我要開始我的功能與$(文件)。就緒(函數(){ ???? –

+0

@CraigJones時間 - 您不必如果您加載它在腳本中在結束正文標記之前添加標記,當我完成我正在處理的網站時,我會盡量擴展我的答案。 –

0

試試這個

<html> 
<head> 
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script> 
<script> 
$("#button").click(function() { 
    $('.transform').toggleClass('transform-active'); 
}); 
</script> 

<style> 
.box { 
    background-color: #218D9B; 
    height: 100px; 
    width: 100px; 
} 

.transform { 
    -webkit-transition: all 2s ease; 
    -moz-transition: all 2s ease; 
    -o-transition: all 2s ease; 
    -ms-transition: all 2s ease; 
    transition: all 2s ease; 
} 

.transform-active { 
    background-color: #45CEE0; 
    height: 200px; 
    width: 200px; 
} 


</style> 
</head> 

<body> 
<div class="box transform"> 
</div> 

<input type="button" id="button" value="Click Me"></input> 
</body> 


</html> 

出現這種情況,你不包括jQuery和使用它嘗試。在腳本標籤的頂部

注意額外的腳本標籤