[英]jquery method in another file not found
我有一個文件“ Site.js”,使用以下方法:
function Init() {
$(document).ready(function() {
//some init actions here
});
}
function jQuery.fn.DivToggle(div) {
$(div).toggle('fast');
//some other animation code here
}
在我的Index.cshtml文件中(我正在使用asp.net mvc),我有以下內容:
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Site.js")" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$(function () {
Init();
});
</script>
</body>
</html>
運行項目時收到此錯誤:“ Microsoft JScript運行時錯誤:'Init'未定義”
知道我在做什么錯嗎?
未定義Init
因為Site.js
存在語法錯誤。
function jQuery.fn.DivToggle(div) {
$(div).toggle('fast');
//some other animation code here
}
您實際上無法做到這一點。 它應該是:
jQuery.fn.DivToggle = function(div) {
$(div).toggle('fast');
//some other animation code here
};
PS $(function(){
與$(document).ready(function(){
$(function(){
$(document).ready(function(){
。您不需要在Init
函數內部使用$(document).ready(function(){
。
我認為真正的問題在於您的DivToggle()函數。 您應該將該代碼更改為以下內容:
(function( $ ) {
$.fn.DivToggle = function() {
$(this).toggle('fast');
};
})( jQuery );
然后,您可以通過創建選擇器並調用它來調用DivToggle。 因此,如果要在頁面中的所有div標簽上運行此代碼,請執行以下操作:
$('div').DivToggle();
以下是有關創建自定義插件的一些文檔: http : //docs.jquery.com/Plugins/Authoring
您可能需要更改調用Init()和document.ready()的方式。 實際上,Init()函數現在實際上並沒有做任何事情。 我認為您可以將代碼更改為此,它將完成您想要的:
<script type="text/javascript">
//create the DivToggle() function
(function( $ ) {
$.fn.DivToggle = function() {
$(this).toggle('fast');
};
})( jQuery );
$(function () {
//call DivToggle() on all <div> tags when the page loads
$('div').DivToggle();
});
</script>
嘗試命名您的javascript:
StackOverflow = {
function Init(){
}
return {
Init: Init
};
}();
調用您的函數
$(function(){
StackOverflow.Init();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.