如何将 jQuery 代码放入一个文件中以供所有页面引用?

发布于 2024-12-08 22:37:56 字数 3324 浏览 0 评论 0原文

我有一个登录弹出窗口,它将在我网站的每个页面上弹出。我想要做的是,一旦用户单击提交,就有一个 JS 文件,其中包含用于处理该请求的 jQuery 代码,并进行 AJAX 调用来验证数据库中的参数。

我能够弹出弹出框。并加载表单。我认为我的 jQuery 代码将存在于一个单独的导入文件中,如下所示:

<script type="text/javascript" >
$(function()
{
    $("input[type=submit]").click(function()
    {
        var some_params= $("#param").val();

        var dataString = 'Some url to send to ajax';

        if( params validated ok )
        {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();
        }
        else
        {
            $.ajax({
                type: "POST",
                url: "/problems/add_problem.php",
                dataType: "json",
                data: dataString,
                success: function(json)
                {
                    $('.success').fadeIn(200).show();
                    $('.error').fadeOut(200).hide();    
                }
            });
        }

        return false;
    });
});
</script>

所以我的问题是如何使该代码仅在提交正确的表单时才被调用?该表单将有一些 id="some_name" 但我真的不明白如何使该 jQuery 代码仅在调用该表单元素时执行。

这是我调用在弹出窗口中显示的表单:

<?php
         echo '<div id="login_div">
         <form id="login_form" method="post" action="">
         <p>
             <label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
         </p>
         <p>
             <label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
         </p>
         <p>
            <input type="submit" value="Log In"  />
         </p>
         </form>
         </div>


<p>
    <a href="http://www.problemio.com/auth/create_profile.php">Create Account</a> | <a href="http://www.problemio.com/auth/forgot_password.php">Reset Pass</a>
</p>
         ';
?>

这是用 jQuery 处理登录表单提交的 Problemio.js 内容:

// javascript library

// login_form

$(function()
{
    $("#login_form input[type=submit]").click(function()
    {
        console.log("test");
        alert("1");
//      var name = $("#problem_name").val();
//      var problem_blurb = $("#problem_blurb").val();

//      var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;

//      if(name=='' || problem_blurb == '')
//      {
//          $('.success').fadeOut(200).hide();
//          $('.error').fadeOut(200).show();
///     }
//      else
//      {
//          $.ajax({
//              type: "POST",
//              url: "/problems/add_problem.php",
//              dataType: "json",
//              data: dataString,
//              success: function(json)
//              {
//                  $('.success').fadeIn(200).show();
//                  $('.error').fadeOut(200).hide();
//                  
///                 // Here can update the right side of the screen with the newly entered information
//                  //alert (json);
//          
//                  new_string = "<h2>Most Recently Added Problems</h2>";

                    // Have to figure out how to make this work with the DOM.

//              }
//          });
//      }

        return false;
    });
});

I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.

I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:

<script type="text/javascript" >
$(function()
{
    $("input[type=submit]").click(function()
    {
        var some_params= $("#param").val();

        var dataString = 'Some url to send to ajax';

        if( params validated ok )
        {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();
        }
        else
        {
            $.ajax({
                type: "POST",
                url: "/problems/add_problem.php",
                dataType: "json",
                data: dataString,
                success: function(json)
                {
                    $('.success').fadeIn(200).show();
                    $('.error').fadeOut(200).hide();    
                }
            });
        }

        return false;
    });
});
</script>

So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.

And here is the form I am calling to display in the popup:

<?php
         echo '<div id="login_div">
         <form id="login_form" method="post" action="">
         <p>
             <label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
         </p>
         <p>
             <label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
         </p>
         <p>
            <input type="submit" value="Log In"  />
         </p>
         </form>
         </div>


<p>
    <a href="http://www.problemio.com/auth/create_profile.php">Create Account</a> | <a href="http://www.problemio.com/auth/forgot_password.php">Reset Pass</a>
</p>
         ';
?>

and here is the problemio.js contents with the jQuery to handle the login form submit:

// javascript library

// login_form

$(function()
{
    $("#login_form input[type=submit]").click(function()
    {
        console.log("test");
        alert("1");
//      var name = $("#problem_name").val();
//      var problem_blurb = $("#problem_blurb").val();

//      var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;

//      if(name=='' || problem_blurb == '')
//      {
//          $('.success').fadeOut(200).hide();
//          $('.error').fadeOut(200).show();
///     }
//      else
//      {
//          $.ajax({
//              type: "POST",
//              url: "/problems/add_problem.php",
//              dataType: "json",
//              data: dataString,
//              success: function(json)
//              {
//                  $('.success').fadeIn(200).show();
//                  $('.error').fadeOut(200).hide();
//                  
///                 // Here can update the right side of the screen with the newly entered information
//                  //alert (json);
//          
//                  new_string = "<h2>Most Recently Added Problems</h2>";

                    // Have to figure out how to make this work with the DOM.

//              }
//          });
//      }

        return false;
    });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

冷情妓 2024-12-15 22:37:56

有两件事。首先,当您将上面的代码放入单独的 javascript 文件中时,请务必删除

接下来,更改以下行:

$("input[type=submit]").click(function()

改为:

$("#loginform input[type=submit]").click(function()

然后在您的

上设置 id="loginform"标签。

Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.

Next, alter the following line:

$("input[type=submit]").click(function()

To instead say:

$("#loginform input[type=submit]").click(function()

And then set id="loginform" on your <form> tag.

唠甜嗑 2024-12-15 22:37:56

您可以使用 .submit() 将处理程序附加到表单提交事件。首先,您需要通过 id 选择您的表单:

$("#some_form_id").submit(function() {
    // the code you have in the click event above goes here.
});

You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:

$("#some_form_id").submit(function() {
    // the code you have in the click event above goes here.
});
做个少女永远怀春 2024-12-15 22:37:56

您可以指定要触发 jquery 的表单。 http://api.jquery.com/submit/

You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/

路弥 2024-12-15 22:37:56

如果您不确定,只需右键单击该网页并阅读其 html 代码。

而且,将函数绑定到 form.submit 比绑定到提交按钮要好得多。

$('formid').submit(function(){blablabla;return false;})

If you are not sure, just right-click this webpage and read its html code.

<script type="text/javascript" src="some.js"></script>

And also, binding the the function to form.submit is much better than to the submit button.

$('formid').submit(function(){blablabla;return false;})

何必那么矫情 2024-12-15 22:37:56

如果您想在不使用 ids 的情况下处理页面上每个提交的点击事件,您始终可以在点击事件中使用 this 关键字来查找发送者,然后找到父表单。

If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文