0

我创建了一个插件,在其中我将标准复选框替换为 iPhone 之类的滑动按钮。我可以将按钮与复选框绑定,即当我单击“是”按钮时,复选框被选中,当我单击“否”按钮时,复选框未被选中。同样,我也为单选按钮创建了一个插件。现在的问题是,如果有人使用 jquery 检查复选框或使用 jquery 选择单选按钮,我如何收听此事件并更改我使用插件创建的相应按钮,因为我无法控制选择的代码单选按钮。

示例代码(我希望在单击按钮时调用更改事件,因为我不控制单击按钮。基本上我想听事件):

<input type="radio" name="radio" id="radio1"> Radio 1 </BR>
<input type="radio" name="radio" id="radio2"> Radio 2 </BR>
<input type="radio" name="radio" id="radio3"> Radio 3 </BR>
<button>click me</button>

$('input:radio').change(function(){
    alert($(this).attr('id') + ' is changed');
});

$('button').click(function(){
    $('#radio1').prop('checked', 'true');
});

http://jsfiddle.net/s24101984/v3Zfn/

4

2 回答 2

1

According to https://stackoverflow.com/a/4836831/280222 it's by design that JavaScript doesn't trigger the event when the check box is updated programatically.

If you have control over the code changing the attribute then you can use:

$('button').click(function(){
    $('#radio1').prop('checked', true).change();
});

In any case: If you're writing a plugin I suggest that you make it an implementation detail that use use a check box underneath the hood. Try to offer a suitable API for your users instead. That would also work this problem.

于 2013-04-07T08:36:52.540 回答
0

好的,我得到了答案,这是已回答此问题的链接 LINK

我们可以为此使用 Hooks,示例:

jQuery.attrHooks.checked = {
    set: function (el, value) {
        el.checked = value;
        $(el).trigger('change');
    }
};

同样,我们也有链接中共享的 propHooks、jsfiddle

http://jsfiddle.net/2nKPY/

于 2013-04-08T20:27:13.567 回答