2015-11-21 28 views
0

我的外部JS文件(example.js):外部JS文件不能運行的Jquery

alert("External js file has just been loaded !"); 

$("#start").click(function (e) { 
    alert("Starting !"); 
}); 

我的HTML文件有<script type="text/javascript" src="example.js"></script>。 當我加載頁面時,它會提示"External js file has just been loaded !",這意味着js文件已成功加載。

但是,當我點擊開始按鈕時,它不會提示"Starting !"

當我插入example.js文件的內容到HTML文件,它可以提醒"Starting !"

<script> 
    alert("External js file has just been loaded !"); 

    $("#start").click(function (e) { 
     alert("Starting !"); 
    }); 
</script> 

如何解決與外部JS這樣一個問題的文件?

+1

您是否在頁面上存在#start元素之前加載example.js文件?您應該在頁面末尾加載js文件,或者將點擊處理程序放入文檔準備就緒的調用中。 – j08691

+0

@ j08691如何在頁面末尾加載js文件? –

+1

將''移至''之前。 – j08691

回答

3

請確保您有您的example.js之前注入你的jquery腳本。

例如:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
<script type="text/javascript" src="example.js"></script> 

,並檢查您的控制檯,如果你得到任何錯誤。

+0

謝謝,它現在有效 –

0

這是因爲您沒有在document.ready函數中寫入單擊事件而發生的。 DOM準備就緒時應該寫入事件。在.ready()使用$.getScript()

$(function() { 
    $.getScript("example.js") 
}) 
+0

我剛試過,但它不起作用。 –

+0

爲什麼downvote ??? – Hiral

1

試裝"example.js"

$(document).ready(function(){ 
    $("#start").click(function (e) { 
    alert("Starting !"); 
    }); 
}); 

你可以在這裏找到更多的細節。

$(document).ready(function() { 
 

 
    $("#world-button").click(function() { 
 
    alert("Hello World"); 
 
    }); 
 

 
});
<!DOCTYPE HTML> 
 
<html> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <title>Demo</title> 
 
</head> 
 
<body> 
 
    <button id="world-button">Hello World</button> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
</body> 
 
</html>