jQuery Mobile点击event.preventDefault似乎不会阻止更改 [英] jQuery Mobile click event.preventDefault does not seem to prevent change

查看:117
本文介绍了jQuery Mobile点击event.preventDefault似乎不会阻止更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图阻止一个单选按钮在用户点击时改变,它在使用标准jQuery时有效但是当你包含jQuery Mobile它似乎不起作用时,我还有什么需要在jQuery Mobile中做的吗? / p>

I am trying to prevent a radio button from changing when a use clicks, it works when using standard jQuery but when you include jQuery Mobile it does not seem to work, is there something else I have to do in jQuery Mobile?

<fieldset data-role="controlgroup"  data-type="horizontal">
        <input type="radio" name="trade-direction" id="buy" value="B" checked="checked" />
        <label for="buy">Buy</label>

        <input type="radio" name="trade-direction" id="hold" value="H"  />
        <label for="hold">Hold</label>

        <input type="radio" name="trade-direction" id="sell" value="S"  />
        <label for="sell">Sell</label>
</fieldset>

$('[name="trade-direction"]:radio').click(function(event) {
    if(!confirm("Do You Want To Change?")) {
        event.preventDefault();
    }
});

下面是jsFiddle中代码的链接。

below is a link to the code in jsFiddle.

http://jsfiddle.net/mikeu/xJaaa/

推荐答案

问题在于,使用jQuery.Mobile,受UI更改影响的元素不是输入元素。实际上,实际上根本没有点击无线电元素。单击的元素是< div class =ui-radio> 。如果要绑定到无线电输入本身,则需要使用更改事件,但在这种情况下它不适用于您,因为该函数在调用之后被调用这个变化已经发生。

The problem is that with jQuery.Mobile, the element that is effected by the UI change is not the input element. In fact, the radio element isn't actually clicked at all. The Element that is clicked is <div class="ui-radio">. If you want to bind to the radio input itself, you need to use the change event, but in this case it won't work for you, because the function gets called after the change has already taken place.

你需要的是这样的:

// Probably a good idea to give your fieldset an ID or class

 $('fieldset').delegate('.ui-radio','click',function(event){
      if(!confirm("Do You Want To Change?")) {
        event.stopImmediatePropagation();
        event.preventDefault();
      } 
  })

event.stopImmediatePropagation()阻止 .ui-radio 触发click事件到输入, event.preventDefault 阻止默认行动。 stopImmediatePropagation 可能没有必要,但它提供了一个额外的保证,可以在不同的浏览器中提供帮助。

The event.stopImmediatePropagation() prevents the the .ui-radio from triggering the click event to the input, and the event.preventDefault prevents the default action. The stopImmediatePropagation may not be necessary, but it gives an added guarantee that may be helpful across different browsers.

这篇关于jQuery Mobile点击event.preventDefault似乎不会阻止更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆