jQuery Mobile click event.preventDefault does not seem to prevent change

对着背影说爱祢 提交于 2019-12-12 20:23:40

问题


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();
    }
});

below is a link to the code in jsFiddle.

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


回答1:


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.

What you need is something like this:

// 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();
      } 
  })

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.



来源:https://stackoverflow.com/questions/16555138/jquery-mobile-click-event-preventdefault-does-not-seem-to-prevent-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!