【问题标题】:jQuery loading animation hide(), show() errorjQuery 加载动画 hide(), show() 错误
【发布时间】:2016-01-29 19:57:44
【问题描述】:

我的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所在的表单也没有隐藏,然后成功消息也没有显示...

我做错了什么,我怎样才能让我的代码变得更好?

【问题讨论】:

  • #my-form 上调用hide() 将隐藏所有子组件——包括#my-btn#loading-img。您还两次将click() 绑定到同一个元素。在单个事件处理程序中添加条件。

标签: javascript jquery ajax show-hide


【解决方案1】:

您正在使用按钮(提交),它会重新加载您的页面。您可以使用 e.preventDefault();或返回假;为了避免重新加载。 查看示例here

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

        // put ajax call here....

        return false;
    });

我还将所有代码放入一个方法中。没有理由有两个点击处理程序。

【讨论】:

    【解决方案2】:

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

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

    类似this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2016-01-08
      相关资源
      最近更新 更多