jQuery加载动画hide(),show()错误

jQuery loading animation hide(), show() error

我的html代码:

<div id="success_message" style="display:none">
    <p>Good job!</p>
</div>
<div id="my-form">
    <form>
        <input>....... (there's lots of inputs)
            <input id="my-btn" type="submit" name="" value="Send" />
            <img id="loading-img" src="images/loading.gif" style="display:none"/>
    </form>
</div>

然后我的javascript在最后:

<script>

    jQuery('#my-btn').click(function () {
        jQuery('#my-btn').hide();
        jQuery('#loading-img').show();
    });


    jQuery("#my-btn").click(function (e) {

        var str = ......... (there's a string)
        jQuery.ajax({
            type: "post",
            url: "/insert.php",
            data: str,
            dataType: "json",
            success: function (result) {
                if (result.success == 1) {
                    jQuery('#loading-img').hide();
                    jQuery('#my-form').hide();
                    jQuery('#success-message').show();
                } else {
                    jQuery('#my-btn').show();
                }
            }
        });
    });
</script>

问题不在于传入的 str 或 ajax 调用,因为我已经用我的代码和数据进行了测试,所有内容都得到执行,然后转到 "if(result.success == 1)"部分代码..

问题是当我点击 "my-btn" 时,它使 "my-btn" 隐藏,但是加载图像没有出现,div 所在的表单也没有'隐藏,然后成功消息也不会显示...

我哪里做错了,我怎样才能使我的代码更好?

您正在使用按钮(提交),它会重新加载您的页面。您可以使用 e.preventDefault();或 return 错误;以免重载。 请参阅示例 here :

jQuery('#my-btn').click(function () {
        jQuery('#my-btn').hide();
        jQuery('#loading-img').show();

        // put ajax call here....

        return false;
    });

另外,我会将所有代码放在一个方法中。没有理由要有两个点击处理程序。

正如 Roman 所说,您可以添加一个 "remove" 提交按钮默认行为,或者将其变成一个按钮。您也可以隐藏按钮并在同一个点击事件中显示加载消息:

    jQuery("#my-btn").click(function (e) {
      jQuery('#loading-img').show();
      jQuery('#my-btn').hide();
    .
    .
    .

类似于this