【问题标题】:Disable button after post using JS/Jquery使用 JS/Jquery 发布后禁用按钮
【发布时间】:2011-01-31 15:49:39
【问题描述】:

我希望有一个功能可以将 onclick 事件添加到我的表单按钮以禁用它们以避免重复发布。

<form>
   <button onclick="disable(this)" type="submit">post</button>
</form>
<script> function disable(button){ $(button). ??? }</script>

有什么想法或提示?谢谢!

【问题讨论】:

    标签: javascript jquery post button


    【解决方案1】:

    按钮必须是 input 元素(如果您不通过 JavaScript 提交表单)。 &lt;button&gt; 元素没有属性 type 并且设置它不会有任何效果。
    我还建议通过 jQuery 附加 click 处理程序:

    <form>
        <!-- ... -->
        <input id="submit" type="submit" value="post" />
    </form>
    <script type="text/javascript>
        $('#submit').click(function() {
            $(this).attr('disabled', true);
        });
    </script>
    

    参考:clickattr

    【讨论】:

    • this.disabled = true 怎么样?
    【解决方案2】:
    $(button).attr('disabled', true);
    

    【讨论】:

    • 如果有的话,应该是$('button')
    • @Felix:我认为他的意图是让它出现在问题的disable 函数中,该函数有一个button 参数,可以从onclick 获取this
    • 我会先在 e 上试试这个,因为它最适合我的代码并让你知道。谢谢大家!
    【解决方案3】:
    <button onclick="this.disabled='disabled'" type...>
    

    【讨论】:

    • onclick 很脏。附加处理程序要好得多
    【解决方案4】:

    如果你只想定位一个按钮:

    $('#buttonID').click(function(){
        $(this).attr('disabled', 'disabled');
    });
    

    如果你想要一个函数:

    function diableButton(bID){
        $(bID).attr('disabled', 'disabled');
    }
    

    使用类似的方式调用它:

    $('#myform').submit(function(){
        disableButton($('input[type=submit]', this));
    });
    

    【讨论】:

    • 如果你在做一个 jQuery .submit(),我不明白你为什么要为 .attr('disabled','disabled') 使用包装函数。
    • Tbh 只是因为用户要求一个功能,如果您在一页上有多个表单并且您只想禁用表单按钮:请参见此处的示例:jsfiddle.net/Scoobler/nKkKR/1 您可能正在使用 ajax在 .submit() 中调用,这样您就不会再为该表单按下按钮了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2014-08-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多