如何在单击时切换单选输入元素的检查状态?

2022-01-21 00:00:00 radio-button jquery javascript

如何在单击元素或其容器时(取消)检查单选输入元素?

How to (un)check a radio input element on click of the element or its container?

我已经尝试了下面的代码,但它并没有取消选中收音机.

I have tried the code below, but it does not uncheck the radio.

HTML:

<div class="is">
    <label><input type="radio" name="check" class="il-radio" /> Is </label>
    <img src="picture" />
</div>

jQuery:

$(".is label, .is ").click(function () {
    if (!$(this).find(".il-radio").attr("checked")) {
        $(this).find(".il-radio").attr("checked", "checked");
    } else if ($(this).find(".il-radio").attr("checked") == "checked") {
        $(this).find(".il-radio").removeAttr("checked");
    }
});

推荐答案

你必须阻止默认行为.目前,点击时会发生以下情况:

You have to prevent the default behaviour. Currently, on click, the following happens:

  1. click 事件触发容器 (div.is).
  2. click 事件触发标签.
  3. 由于您的函数切换了一个状态,并且事件监听器被调用了两次,结果似乎什么都没有发生.
  1. click event fires for the container (div.is).
  2. click event fires for the label.
  3. Since your function toggles a state, and the event listener is called twice, the outcome is that nothing seems to happen.

更正的代码(http://jsfiddle.net/nHvsf/3/):p>

Corrected code (http://jsfiddle.net/nHvsf/3/):

$(".is").click(function(event) {
    var radio_selector = 'input[type="radio"]',
        $radio;

    // Ignore the event when the radio input is clicked.
    if (!$(event.target).is(radio_selector)) {
        $radio = $(this).find(radio_selector);
        // Prevent the event to be triggered
        // on another element, for the same click
        event.stopImmediatePropagation();
        // We manually check the box, so prevent default
        event.preventDefault();
        $radio.prop('checked', !$radio.is(':checked'));
    }
});
$(".il-radio").on('change click', function(event) {
    // The change event only fires when the checkbox state changes
    // The click event always fires

    // When the radio is already checked, this event will fire only once,
    //   resulting in an unchecked checkbox.
    // When the radio is not checked already, this event fires twice
    //   so that the state does not change
    this.checked = !this.checked;
});

相关文章