开发者

Custom jQuery Functions

开发者 https://www.devze.com 2023-04-13 00:26 出处:网络
I am trying to understand how to write custom functions in jquery. I have this code: <head> . . <script src=\"js/jquery.js\"></script>

I am trying to understand how to write custom functions in jquery.

I have this code:

<head>
.
.
<script src="js/jquery.js"></script>
<script>
     $(document).ready(function(){
       $("createaccountbtn").click(function(e){            
            e.preventDefault();
            alertMe();
       });
     });

     (function( $ ) {
        $.fn.alertMe = function() {
          alert("hello world!");
        };
     })( jQuery );
</script>
</head>

<body>
<h1>Create Account</h1>
<div id = "wrapper">
<form name = "createaccountform" action = "php/createaccount.php" method = "post">
<p>First Name<input name = "fName" type="text" size="25"/><label id ="fNameStatus"></label></p>

<p>Last Name<input name = "lName" type="te开发者_Python百科xt" size="25"/><label id ="lNameStatus"></label></p>

<p>E-mail<input name = "email" type="text" size="25"/><label id ="emailStatus"></label></p>

<p>Confirm E-mail<input name = "email" type="text" size="25"/><label id ="emailStatus"></label></p>

<p>Password<input name = "pass" type="text" size="25"/><label id ="passwordStatus"></label></p>

<p>Confirm Password<input name = "cpass" type="text" size="25"/><id name ="cpasswordStatus"></label></p>

<p><input id = "createaccountbtn" type ="button" value="Create Account"/></p>
</form>
</div>
</body>

I am trying to execute a custom function when the user clicks the "Create Account" button, but I cannot get it to work. Any ideas what's up?


This code:

(function( $ ) {
    $.fn.alertMe = function() {
      alert("hello world!");
    };
})( jQuery );

adds a function called alertMe to the jQuery prototype, which will let you call $("div").alertMe();

To call it as you are, just declare a regular function:

function alertMe () {
    alert("hello world!");
}

Also, $("createaccountbtn") is not a valid selector, as it will try to select anything with a tagName of createaccountbtn - make sure to prepend it with a #.


Wont it be simpler if...

$(document).ready(function(e){
e.preventDefault();
$("#createaccountbtn").click(function(){            
alertMe();
});

function alertMe(){
alert('Hello World');
}
});


Script section need to be updated as follows -

<script>
 $(document).ready(function(){
   $("#createaccountbtn").click(function(e){            
        e.preventDefault();

        alertMe();
   });
 }


 );

 function alertMe()
 {
 alert("hello world!");
 }

</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号