【问题标题】:Custom jQuery Functions自定义 jQuery 函数
【发布时间】:2011-10-12 12:26:55
【问题描述】:

我正在尝试了解如何在 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>

当用户单击“创建帐户”按钮时,我正在尝试执行自定义功能,但我无法让它工作。有什么想法吗?

【问题讨论】:

    标签: javascript jquery html function methods


    【解决方案1】:

    这段代码:

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

    在 jQuery 原型中添加一个名为 alertMe 的函数,它可以让你调用 $("div").alertMe();

    要按原样调用它,只需声明一个常规函数:

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

    另外,$("createaccountbtn") 不是一个有效的选择器,因为它会尝试选择标签名称为 createaccountbtn 的任何内容 - 请确保在其前面加上 #

    【讨论】:

      【解决方案2】:

      如果...会更简单

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

      【讨论】:

        【解决方案3】:

        脚本部分需要更新如下-

        <script>
         $(document).ready(function(){
           $("#createaccountbtn").click(function(e){            
                e.preventDefault();
        
                alertMe();
           });
         }
        
        
         );
        
         function alertMe()
         {
         alert("hello world!");
         }
        
        </script>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-08
          • 2013-02-07
          • 2014-02-15
          • 1970-01-01
          • 1970-01-01
          • 2023-03-27
          • 1970-01-01
          • 2012-02-27
          相关资源
          最近更新 更多