简体   繁体   English

点击后如何检查单选按钮是否已被检查?

[英]How to check if a radiobutton was already checked, after it has been clicked?

I have a click listener on my radiobuttons. 我的radiobuttons上有一个点击监听器。

I need to check whether a radiobutton was already checked prior to the click, or if it wasnt. 我需要检查在点击之前是否已检查过radiobutton,或者是否已经检查过。

$('.GridRadio').live('click', function () {
    alert($(this).is(':checked'));
});

However, the above alerts true every time. 但是,上述警报每次都是真实的。 How can i see if it was checked already, prior to when being clicked? 如何在点击之前查看是否已经检查过?

You could use data() to store the previous value of the radio, and then check the current value against that: 您可以使用data()来存储收音机的先前值,然后根据该值检查当前值:

$(".GridRadio").click(function() {
    var lastValue = $(this).data("last-value");
    var value = $(this).val();

    if (lastValue == value) {
        alert("Already checked");
    }
    else {
        alert("Not previously checked");
    }

    $(".GridRadio").data("last-value", "");
    $(this).data("last-value", value);
});

Example fiddle 示例小提琴

If you set the checked attribute on one of the radios in HTML on page load, add this code to set the data for that specific one: 如果在页面加载时在HTML中的某个无线电上设置checked属性,请添加此代码以设置该特定data

$(".GridRadio:checked").data("last-value", $(".GridRadio:checked").val())

If you're using live you probably append $('.GridRadio') after $(document).ready . 如果你正在使用live你可能会在$(document).ready之后附加$('.GridRadio') if that's right - you can do this check when you append it. 如果那是对的 - 你可以在追加时进行检查。 then when it is being clicked - it will always be the negative value. 然后当它被点击时 - 它将永远是负值。

(and if it is in the page from the beginning - you can do this check once the page is reloaded, before someone clicks on it.) (如果它从头开始在页面中 - 您可以在重新加载页面之后进行此检查,然后再有人点击它。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM