2011-10-12 118 views
-1

我想了解如何编写自定义功能的jQuery。自定义jQuery函数

我有这样的代码:

<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="text" 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> 

我想,当用户单击“创建帐户”按钮,执行自定义函数,但我不能得到它的工作。任何想法是怎么回事?

回答

4

此代码:

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

添加了一个名为alertMe到jQuery的原型功能,可以让你打电话$("div").alertMe();

要调用它作为你,只是声明了一个常规的功能:

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

而且,$("createaccountbtn")是不是一个有效的选择,因为它会尝试与标记名来选择任何内容3210 - 请务必在#之前加上它。

2

惯于它是简单的,如果...

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

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

固定它,我们对此深感抱歉。 – JohnSmith

0

脚本部分需要按以下方式进行更新 -

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

     alertMe(); 
    }); 
} 


); 

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

</script>