I have a file- "Site.js" with the following method:
function Init() {
$(document).ready(function() {
//some init actions here
});
}
function jQuery.fn.DivToggle(div) {
$(div).toggle('fast');
//some other animation code here
}
in my Index.cshtml file (I'm using asp.net mvc), I have this:
<!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>
I get this error when I run the project: "Microsoft JScript runtime error: 'Init' is undefined"
Any idea what I'm doing wrong?
Init
is not defined because there is a syntax error in Site.js
.
function jQuery.fn.DivToggle(div) {
$(div).toggle('fast');
//some other animation code here
}
You can't actually do that. It should be:
jQuery.fn.DivToggle = function(div) {
$(div).toggle('fast');
//some other animation code here
};
PS $(function(){
is the same as $(document).ready(function(){
. You don't need the $(document).ready(function(){
inside your Init
function.
I think the real problem is with your DivToggle() function. You should change that code to the following:
(function( $ ) {
$.fn.DivToggle = function() {
$(this).toggle('fast');
};
})( jQuery );
Then you can call DivToggle by creating a selector and calling it. So if you want to run this on all of the div tags in your page do this:
$('div').DivToggle();
Here is some documentation on creating custom plugins: http://docs.jquery.com/Plugins/Authoring
You probably need to change the way you are calling Init() and document.ready(). Actually the Init() function isn't really doing anything right now. I think you can change your code to this and it would accomplish what you want:
<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>
Try namespacing your javascript:
StackOverflow = {
function Init(){
}
return {
Init: Init
};
}();
Call your function with
$(function(){
StackOverflow.Init();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.