【问题标题】:Ignore multiple button taps after first one on iPhone webapp using jQuery Mobile?使用 jQuery Mobile 在 iPhone webapp 上的第一个按钮后忽略多个按钮点击?
【发布时间】:2012-03-07 21:20:02
【问题描述】:

在使用 jQuery Mobile 构建的 HTML5 webapp 中假设按钮 A。

如果有人点击按钮 A,我们调用 foo()。即使用户双击按钮 A, Foo() 也应该被调用一次。

我们尝试使用 event.preventDefault(),但这并没有阻止第二次点击调用 foo()。 event.stopImmediatePropagation() 可能会起作用,但它也会阻止其他方法进一步向上堆栈,并且可能不会导致干净的代码维护。

其他建议?维护一个跟踪变量似乎是一个非常丑陋的解决方案,而且是不可取的。

【问题讨论】:

    标签: iphone ios html jquery-mobile


    【解决方案1】:

    您可以设置一个标志并检查是否可以运行 foo() 函数或在您不希望用户能够使用它的时间取消绑定事件,然后在 a 之后重新绑定事件处理程序延迟(只有几个选项)。

    这就是我要做的。我会使用超时来排除后续事件:

    $(document).delegate('#my-page-id', 'pageinit', function () {
    
        //setup a flag to determine if it's OK to run the event handler
        var okFlag = true;
    
        //bind event handler to the element in question for the `click` event
        $('#my-button-id').bind('click', function () {
    
            //check to see if the flag is set to `true`, do nothing if it's not
            if (okFlag) {
    
                //set the flag to `false` so the event handler will be disabled until the timeout resolves
                okFlag = false;
    
                //set a timeout to set the flag back to `true` which enables the event handler once again
                //you can change the delay for the timeout to whatever you may need, note that units are in milliseconds
                setTimeout(function () {
                    okFlag = true; 
                }, 300);
    
                //and now, finally, run your original event handler
                foo();
            }
        });
    });
    

    【讨论】:

    • 我知道提到的原始问题没有使用跟踪变量,但是,经过 3 小时的谷歌搜索和反复试验,这是一种享受!来自我的 +1。
    • 是的,如果您没有进入单独的变量,您也可以将标志变量存储为 jQuery 数据。 $.data(this, 'flag', [state])
    【解决方案2】:

    我在这里创建了一个示例http://jsfiddle.net/kiliman/kH924/

    如果您使用<a data-role="button"> 类型的按钮,则没有“禁用”状态,但您可以添加适当的类以使其具有禁用外观。

    在您的事件处理程序中,检查按钮是否具有ui-disabled 类,如果是,您可以立即返回。如果没有,添加ui-disabled 类,然后调用foo()

    如果您想重新启用该按钮,只需删除该类即可。

    $(function() {
        $('#page').bind('pageinit', function(e, data) {
            // initialize page
            $('#dofoo').click(function() {
                var $btn = $(this),
                    isDisabled = $btn.hasClass('ui-disabled');
                if (isDisabled) {
                    e.preventDefault();
                    return;
                }
                $btn.addClass('ui-disabled');
                foo();
            });
        });
    
        function foo() {
            alert('I did foo');
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多