2012-02-11 124 views
0

我很抱歉爲你提出這樣一個簡單的問題。我可以在我的html頁面中使用jQuery函數。但我不知道如何使用我的JavaScript源文件中的一個?請告訴我。如何在我的JavaScript源代碼中使用jQuery功能?

預先感謝您。

編輯:目前,我在我的JavaScript源文件的頭部使用以下聲明。

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> 

回答

4

你可以用完全相同的方法來做到這一點。在將外部JS文件與jQuery鏈接起來之前,您只需鏈接jQuery源文件,以便知道如何處理它。

下面是託管的jquery一個例子:

的test.html

<html> 
    <head> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> 
    <script type="text/javascript" src="./test.js"></script> 
    </head> 
</html> 

test.js

$(document).ready(function(){ 
    var t = $.trim(" abc "); 
    alert('...'+t+'...'); 
}); 

這裏是嵌入的jquery一個例子:

的test.html

<html> 
    <head> 
    <script type="text/javascript" src="./jquery-1.7.1.min.js"></script> 
    <script type="text/javascript" src="./test.js"></script> 
    </head> 
</html> 

test.js

(function($){ 
    var t = $.trim(" abc "); 
    alert('...'+t+'...'); 
})(jQuery); 
+0

能不能請您給我一個簡短的示例代碼? – 2012-02-11 14:06:53

+0

借用你的test.js,如何使用jQuery.trim(「abc」)?雖然這聽起來很不禮貌,但警告並不適合作爲示例。請重新安排test.js。 – 2012-02-11 14:31:46

+0

哇。這完全是無禮的。我已經屈服於你的要求,但如果你有特定的要求,你應該在你的問題中提出要求。 – 2012-02-11 14:40:03

1

你的意思是你不知道怎麼會這樣,它影響以後的DOM元素,將其添加到該文件的標題它?就像wescrow所說的,你應該先導入jQuery文件,然後導入你的腳本文件。然後,在你的腳本文件,請確保您有類似:

$(document).ready(function(){ 
    // your javascript here 
}); 

$(function(){ 
    // your javascript here 
}); 

這可以確保您的DOM在jQuery代碼踢之前加載欲瞭解更多信息,請參閱官方doc:http://api.jquery.com/ready/他們在那裏有一個很好的例子。

1

這裏還有什麼可以快速使用jQuery敲了一個小的味道:

$(function(){ 
    // Few lines of code will query Twitter's search API and append the results to the browser. 
    var url = "http://search.twitter.com/search.json?callback=?&q=weather"; 

    $.getJSON(url, function(data){ 
    $.each(data.results, function(i, tweet){ 
     $('body').append("<p>" + tweet.text + " by " + tweet.from_user_name + "</p>"); 
    }); 
    }); 
});