javascript 如何在按钮单击时调用 jquery 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25472835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:33:25  来源:igfitidea点击:

How to call jquery function on button click?

javascriptjqueryhtml

提问by shakti sharma

I am creating a small college project in PHP where I want to submit a form without refresh. I am using the following code, but it is not working as I expected.

我正在用 PHP 创建一个小型大学项目,我想在其中提交一个表单而无需刷新。我正在使用以下代码,但它没有按我预期的那样工作。

usercss/demo.js

usercss/demo.js

function newleadentryform(){

document.getElementById('RightPaneContainerDiv').innerHTML="<div id='leadgenerationformdiv'>"+
"<form  id='form' 'action='#'>"+
"<table width='352' border='0' class='CSSTableGenerator' style='width: 45%;'>"+
"<tr>"+
"<td>&nbsp</td>"+
"<td>&nbsp;</td>"+
"</tr>"+
  "<tr>"+
    "<td class='leadgenerationformcss'>Lead Owner</td>"+
    "<td><input name='leadowner' type='text' class='leadgenerationtextboxcss' id='leadowner' /></td>"+
  "</tr>"+
"<tr>"+
    "<td>"+
    "<input type='button' id='submit'  name='submit' value='Update' onclick='leadgenerationformvalidation()'/>"+
    "</td>"+
    "<td><input type='reset' value='reset'></td>"+
  "</tr>"+
"</table>"+
"</form>"+
"</div><!-- leadgenerationformdiv-->";  

}

index.php

索引.php

<!DOCTYPE html>
<html>
    <head>
        <title>Examples of using jQuery Alerts</title>
        <script src="jquery.js" type="text/javascript"></script>
        <script src="jquery.ui.draggable.js" type="text/javascript"></script>

        <script src="jquery.alerts.js" type="text/javascript"></script>
        <link href="jquery.alerts.css" rel="stylesheet" type="text/css" media="screen" />

        <!-- Example script -->
        <script type="text/javascript">
            $(document).ready( function() {
                $("#submit").click( function() {
                    jAlert('Example of a basic alert box in jquery', 'jquery basic alert box');
                });
            });
        </script>
        <script src="userjs/demo.js"></script>
    </head>
    <body>
    </body>
    <a href="#" class="headerAnchorClass" onclick='newleadentryform()'>New Lead</a>
    </p>
    <div id="RightPaneContainerDiv" style=" float: left; margin-left: 11px; overflow-y: auto; height: 90vh;">
    </div>
</html>

When I click on "New Lead" -link, a form should open, which contains a text field and an "Update" button, which should then submit the form without refresh.

当我单击“新潜在客户”链接时,应打开一个表单,其中包含一个文本字段和一个“更新”按钮,然后应在不刷新的情况下提交表单。

How can I achieve what I am trying to do here? Thanks in advance.

我怎样才能在这里实现我想要做的事情?提前致谢。

采纳答案by ascx

You should be using AJAXfor such. Also, fetching an HTML form through a function is not necessarily the best way, especially because you have static content in that form. It should be on the loaded page but instead of showing it, it should be hidden from the client until you click the New Leadlink on the page.

您应该为此使用AJAX。此外,通过函数获取 HTML 表单不一定是最好的方法,尤其是因为该表单中有静态内容。它应该在加载的页面上,但不是显示它,而是应该对客户端隐藏,直到您单击页面上的New Lead链接。

So, what do you need to do in order to catch a click?You already figured it out by using the deprecated(not officially deprecated, yet) click-function, which is triggered when a click event occurs. However, it is adviced to use the on-function instead, and within that you should define your event and other arguments.

那么,你需要做什么才能抓住点击?您已经通过使用已弃用(尚未正式弃用)的click函数弄清楚了,该函数在单击事件发生时被触发。但是,建议改用on函数,并在其中定义事件和其他参数。

In order to skip the actual click event and disable page refreshing(it actually submitsit as a real form on the specified method and action) we must use the preventDefault-function to cancel the default action, which in this case is the default browser behavior: submit a form when a submit button is pressed.

为了跳过实际的点击事件并禁用页面刷新(它实际上在指定的方法和操作上将其作为真实表单提交),我们必须使用preventDefault-function取消默认操作,在这种情况下是默认浏览器行为: 按下提交按钮时提交表单。

So now what we end up with is the actual sending of the form. In order to send it to the server, we should be using AJAX, like I mentioned in the beginning of the answer.

所以现在我们最终得到的是表单的实际发送。为了将它发送到服务器,我们应该使用 AJAX,就像我在答案开头提到的那样。

What AJAX does, is it basically creates an XMLHttpRequest objectand sends it to the server to process and create a response to. The server then sends it back to the client, which reads it while the session is active. Websites that use this type of techique (or similar techniques) are known as dynamic webpages, where content may change during a session.

AJAX 所做的基本上是创建一个XMLHttpRequest 对象并将其发送到服务器以进行处理并创建响应。然后服务器将其发送回客户端,客户端在会话处于活动状态时读取它。使用这种技术(或类似技术)的网站被称为动态网页,其中的内容可能会在会话期间发生变化。

So what we do, is we create and send our request to the server for processing, and it then returns us something, which the client will then process and figure out. In this case I made it rather simple, and I am checking for the existance of the post field, and the length of the post field. If the post field does not exist, it will return bad-post. And if the value is less or more than my specified amount, which in this case is five(5) and twenty(20), it will return bad-length. But if all went well, it will return success, which is the response the client is normally expecting. This is then processed client-side and the browser will output an alert box to the client explaining what we just received.

所以我们所做的是,我们创建请求并将其发送到服务器进行处理,然后它返回给我们一些东西,然后客户端将对其进行处理和计算。在这种情况下,我让它变得相当简单,我正在检查 post 字段的存在,以及 post 字段的长度。如果 post 字段不存在,它将返回bad-post。如果该值小于或大于我指定的数量,在本例中为(5) 和二十(20),它将返回bad-length。但是如果一切顺利,它会返回success,这是客户端通常期望的响应。然后在客户端进行处理,浏览器将向客户端输出一个警告框,解释我们刚刚收到的内容。

index.php

索引.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Examples of using jQuery Alerts</title>

        <link href="jquery.alerts.css" rel="stylesheet" media="screen" />

        <style>
            #lead-container {
                margin-left: 11px;
                display: none;
                height: 90vh;
                float: left;
            }

            #lead-container form {
                border: 0;
                width: 45%;
            }
        </style>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>
        <a href="#" id="create-new-lead">New Lead</a>

        <div id="lead-container">
            <form name="lead-creator">
                <table>
                    <tr>
                        <td>Lead Owner</td>
                        <td>
                            <input type="text" id="lead-owner-field" name="lead-owner" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="submit" id="submit-button" name="submit" value="Update" />
                        </td>
                        <td>
                            <input type="submit" id="reset-button" name="reset" value="Reset" />
                        </td>
                    </tr>
                </table>
            </form>
        </div>

        <script>
            var isBeingSent = false;

            $(document).ready(function(){
                // We want to prevent default browser behavior when clicking the input buttons or the "New Lead" link
                $("#create-new-lead, #submit-button, #reset-button").on("click", function(e){
                    e.preventDefault();
                });

                // We want to display the lead-container when we click the "New Lead" link
                $("#create-new-lead").on("click", function(){
                    if (!$("#lead-container").is(":visible"))
                        $("#lead-container").show();
                });

                $("#submit-button").on("click", function(){
                    // We stop executing the event if the operation is already running
                    if (isBeingSent == true)
                        return false;

                    // We mark the operation running to avoid simultaneous actions
                    isBeingSent = true;

                    // We send a post request to the server
                    $.post(
                        "handler.php", // The file, which we are sending data to
                        { leadowner: $("#lead-owner-field").val() }, // The data, which we are sending
                        function(result){ // The returning function when the operation is complete
                            isBeingSent = false;

                            if (window.console)
                                console.log('Returned: [' + typeof(result) + '] ' + result);

                            if (result == "success") {
                                alert('All went well!');
                            }else if (result == "bad-length") {
                                alert('Hmm, the value is too small, or too lengthy!');
                            }else if (result == "bad-post") {
                                alert('Ouch, something went very, very wrong...');
                            }else{
                                alert('Wops! Returned: [' + typeof(result) + '] ' + result + '.');
                            }
                        }
                    );
                });

                // We reset the input field when we click the "Reset" button
                $("#reset-button").on("click", function(){
                    $("#lead-owner-field").val("");
                });
            });
        </script>

        <script src="jquery.ui.draggable.js"></script>
        <script src="jquery.alerts.js"></script>
    </body>
</html>

handler.php

处理程序

<?php
    // Did the client send us a valid post request?
    if (!isset($_POST["leadowner"]))
        die("bad-post");

    // Sanitize and finalize the input value
    $finalizedValue = preg_replace("/[^\w\s\.\-]/", "", $_POST["leadowner"]);

    // Compare the length of the input value against our specified values
    if (strlen($finalizedValue) < 5 || strlen($finalizedValue) > 20)
        die("bad-length");

    // If all went well, just return a success message
    die("success");
?>

I hope this helped you out with your problem.

我希望这能帮助你解决你的问题。

EDIT:Improved code layout and added comments to explain the functionality.

编辑:改进了代码布局并添加了注释来解释功能。

回答by jirigracik

You may better include html from file, not insert it as a string. You will see possible mistakes and it is a lot better editable. Or you may include it on page and hide it via css on the begining, then on clicking the "New lead" link just call $('form').show();. When you click update button, you want probably do an AJAX call, which can be easily done with the jQuery form plugin. Just include it and on the "Update" button click call $('form').ajaxForm({url: 'filethatsavesyourpostdata.php', type: 'post'})

您最好从文件中包含 html,而不是将其作为字符串插入。您会看到可能的错误,而且它的可编辑性要好得多。或者您可以将它包含在页面上并在开始时通过 css 隐藏它,然后单击“新潜在客户”链接只需调用$('form').show();. 当您单击更新按钮时,您可能想要执行 AJAX 调用,这可以使用 jQuery 表单插件轻松完成。只需包含它并在“更新”按钮上单击调用$('form').ajaxForm({url: 'filethatsavesyourpostdata.php', type: 'post'})

回答by Jyoti Puri

You can do it like:

你可以这样做:

<!DOCTYPE html>
<html>

<head>
  <title>Examples of using jQuery Alerts</title>
  <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <!-- Example script -->
  <script type="text/javascript">
    $(document).ready(function() {
      $("#submit").click(function() {
        alert('Example of a basic alert box in jquery', 'jquery basic alert box');
      });
      $("#testing").click(function() {
        $("#RightPaneContainerDiv").show();
      });
    });
  </script>
  <script src="userjs/demo.js"></script>
</head>

<body>
  <a href="#" id="testing" class="headerAnchorClass" onclick="newleadentryform()">New Lead</a>
  <p></p>
  <div id="RightPaneContainerDiv" style="display:none;float: left; margin-left: 11px; overflow-y: auto; height: 90vh;">
    <div id='leadgenerationformdiv'>
      <form id='form' action='#'>
        <table width='352' border='0' class='CSSTableGenerator' style='width: 45%;'>
          <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr>
            <td class='leadgenerationformcss'>Lead Owner</td>
            <td>
              <input name='leadowner' type='text' class='leadgenerationtextboxcss' id='leadowner' />
            </td>
          </tr>
          <tr>
            <td>
              <input type='button' id='submit' name='submit' value='Update' onclick='leadgenerationformvalidation()' />
            </td>
            <td>
              <input type='reset' value='reset'>
            </td>
          </tr>
        </table>
      </form>
    </div>

  </div>
</body>

</html>

Check plunker: http://plnkr.co/edit/ODJB24Y6q5xT8jvZjFNM?p=preview

检查 plunker:http://plnkr.co/edit/ODJB24Y6q5xT8jvZjFNM?p=preview