0

我在一个页面上有两个复选框,默认情况下选中一个。我想在单击任一复选框时使用 jQuery 触发自定义事件。但是,问题是我想在单击事件之前checked获取选中的值,但我一直在获取as true

我的 HTML 如下所示:

<div class="clearfix controls">
    <label class="radio inline" for="yes">
        <input type="radio" name="recycle" value="1" id="yes" data-price-increase="29">
        Yes
    </label>
    <label class="radio inline" for="no">
        <input type="radio" name="recycle" value="0" id="no" checked="checked" data-price-decrease="29">
        No
    </label>
</div>

我的 JavaScript 看起来像这样:

$('[data-price-increase]').on('click', function(e) {
    $('body').trigger('price.increase', [ $(this).data('price-increase') ]);
});
$('[data-price-decrease]').on('click', function(e) {
    $('body').trigger('price.decrease', [ $(this).data('price-decrease') ]);
});

但是,如果我连续单击一个单选按钮,即使它已经被选中,单击处理程序也会被多次触发。

单选按钮分别添加或删除额外费用,因此不断单击“是”单选按钮会不断将费用添加到价格中,这是不希望的。如果已经选中“是”,那么我不希望再次添加该值。

4

2 回答 2

3

我认为您正在寻找更改事件:

$('[data-price-increase]').on('change', function(e) {
    console.log('changed');
    $('body').trigger('price.increase', [ $(this).data('price-increase') ]);
});
$('[data-price-decrease]').on('change', function(e) {
    console.log('changed');
    $('body').trigger('price.decrease', [ $(this).data('price-decrease') ]);
});

因此,仅在检查更改时才会触发操作,而不是在每次单击时触发。

于 2013-02-13T10:59:19.263 回答
-2

询问目标是否已检查

$('[data-price-increase]').on('click', function(e) {
   if(!jQuery(event.target).is(":checked"))
       $('body').trigger('price.increase', [ $(this).data('price-increase') ]);
});
于 2013-02-13T11:01:25.913 回答