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

How to toggle the check state of a radio input element on click?

本文关键字:元素 输入 检查 状态 单选 单击      更新时间:2023-09-26

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

我试过下面的代码,但它没有取消选中收音机。

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");
    }
});

您必须防止默认行为。目前,点击后,会发生以下情况:

  1. 为容器(div.is)激发click事件
  2. 为标签激发click事件
  3. 由于您的函数切换一个状态,并且事件侦听器被调用两次,因此结果是似乎什么都没有发生

已更正代码(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;
});

单选按钮不取消选中,您需要使用复选框(type='checkbox')

只使用html,相同的功能

<label for="rdio"><input type="radio" name="rdio" id="rdio" class="il-radio"  /> Is </label>