Jquery 如何在单选按钮上获取onchange回调,但仅限于已设置的按钮

Jquery 如何在单选按钮上获取onchange回调,但仅限于已设置的按钮,jquery,jquery-mobile,radio-button,onchange,Jquery,Jquery Mobile,Radio Button,Onchange,我有一组同名但值不同的单选按钮。我想做一些类似的事情: $("#langs").on("change", "[name=locale]", myfunction); <div data-role="fieldcontain"> <fieldset data-role="controlgroup" data-type="horizontal"> <input type="radio" name="langs" id="first" value="

我有一组同名但值不同的单选按钮。我想做一些类似的事情:

$("#langs").on("change", "[name=locale]", myfunction);
<div data-role="fieldcontain">
     <fieldset data-role="controlgroup" data-type="horizontal">
     <input type="radio" name="langs" id="first" value="1" onchange="myfunction();"/>
     <label for="first">First</label>
     <input type="radio" name="langs" id="second" value="2" onchange="myfunction();"/>
     <label for="second">Second</label>
     </fieldset>
</div>
这是可行的,但当我点击一个新单选按钮时,我的函数会被调用两次:一次是自动取消选中的“旧”单选按钮,一次是我点击的新单选按钮


将onchange更改为onclick并不是一个解决方案,因为我在jquery mobile中使用它,并且它用标签包装输入,因此单击的是标签,而不是输入。

据我所知,在标签中使用onclick event和jquery没有任何限制。如果你有身份证,你可以使用它。 假设您有以下html:

<label for="foo" id="whatever1">foo</label><input type="radio" name="radiogroup_0" value="foo" >
<label for="bar" id="whatever2">bar</label><input type="radio" name="radiogroup_1" value="bar" >
另一个单选按钮的标签也是如此

$('#whatever1').click(
  function(){
    //paste your code inside
  }
);
希望这有帮助。
路易斯·M.

试一试如下:

$("#langs").on("change", "[name=locale]", myfunction);
<div data-role="fieldcontain">
     <fieldset data-role="controlgroup" data-type="horizontal">
     <input type="radio" name="langs" id="first" value="1" onchange="myfunction();"/>
     <label for="first">First</label>
     <input type="radio" name="langs" id="second" value="2" onchange="myfunction();"/>
     <label for="second">Second</label>
     </fieldset>
</div>
这应该只调用函数一次,因为它包含在需要使用它的元素中。

您可以将
$(This)
作为参数传递给
myfunction
,然后在
myfunction
中检查是否选中了单选按钮

$(“#langs”).on(“更改”,“名称=区域设置]”,function(){myfunction($(this));})


这对你有用吗?遵循

  • (乐趣)
HTML:


我可能做错了什么,但我必须执行$(elem).is(':checked')才能使其正常工作。从jQuery 1.7开始,bind()已被弃用,绑定事件的首选方法是.on()(直接从文档中获得)。
function myfunction(elem) {
    if(elem.is(':checked')) {
        // code here
    }
}
<div data-role="page"> 
    <fieldset data-role="controlgroup">
        <legend>Choose a language:</legend>
        <input type="radio" name="langs" id="english-lang" value="en" />
        <label for="english-lang">English</label>
        <input type="radio" name="langs" id="korean-lang" value="ko" />
        <label for="korean-lang">Korean</label>
    </fieldset>
</div>​
$("input[name=langs]:radio").bind( "change", function(event, ui) {
    console.log('Lang: '+$(this).val());

    // Call function here
});