2

我试图阻止单选按钮在用户点击时发生变化,它在使用标准 jQuery 时有效,但是当你包含 jQuery Mobile 时它似乎不起作用,在 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 中代码的链接。

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

4

1 回答 1

4

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

你需要的是这样的:

// 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触发输入的点击事件,并防止event.preventDefault默认动作。这stopImmediatePropagation可能不是必需的,但它提供了额外的保证,可能对不同的浏览器有所帮助。

于 2013-05-15T01:59:11.100 回答