如果在FORM标签内部,为什么button.click()事件不起作用?

时间:2012-11-16 13:12:55

标签: jquery forms onclick

以下JQuery“表单”有效(通过ajax发送和接收数据)但如果我更改

 <div id="formContact">

form标记,然后它不起作用。 为什么会这样?

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Testing - Test</title>
        <meta name="keywords" content="" />
        <meta name="description" content="" />
        <script type="text/javascript" src="systemJavascript/jquery-1.4.4.min.js"></script>
        <style type="text/css">

            #result {
                margin: 10px;
                background: #eee;
                padding: 10px;
                height: 40px;
                overflow: auto;
            }
        </style>
        <script type="text/javascript">
            $(function() {
                $('#resultArea').html('click button');
                $('button#formButton').click(function() {
                    console.log('we only get here if form is a DIV element, not a FORM element');
                    $('button#formButton').blur();
                    $('#firstName').focus();
                    $.post(
                    'testAjaxProcess2.php',
                    {
                        firstName: $('#firstName').val(),
                        lastName: $('#lastName').val()
                    },
                    function( jsonString )
                    {
                        var data = $.parseJSON(jsonString);
                        $('div#resultArea').html(data['message']);
                    });
                });
            });

        </script>
    </head>
    <body>
        <h2>Form</h2>
        <div id="formContact">
            <div>First Name:<input type="text" id="firstName"/></div>
            <div>Last Name:<input type="text" id="lastName"/></div>            
            <div><button id="formButton">Send</button></div>
        </div>
        <h2>Result</h2>
        <div id="resultArea">
        </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:5)

最佳猜测 - 默认情况下,button将充当表单的提交按钮。您希望阻止点击处理程序中的默认操作停止此操作:

$('button#formButton').click(function(e) { // assign event object
  e.preventDefault( ); // Stop the form being submitted.
  console.log('we only get here if form is a DIV element, not a FORM element');
});

编辑:我刚用jsfiddle证实了这一点:http://jsfiddle.net/Y2MdZ/