$(".dist_radio").click(function() {
        $(this).attr("class", "dist_radio dist_on");
        if (!$(this)) {
            $(".dist_on").attr("class", "dist_radio");
        }


        console.log($(this).attr("class"));
    });

I'm using this code to style radio buttons and it sort of works apart from the fact that when I click on another button, the rest don't get dist_on class removed. Can you please tell me what's wrong with it?

有帮助吗?

解决方案

Use the .not method:

$(".dist_radio").not(this).attr("class", "dist_radio");

But for your logic, you could just do like below (use addClass/removeClass instead of changing the class attribute directly):

$(".dist_radio").click(function() {
    $(".dist_radio").removeClass('dist_on');
    $(this).addClass('dist_on');
});

其他提示

You can use .not():

Remove elements from the set of matched elements.

$(".dist_radio").click(function () {
    $(this).attr("class", "dist_radio dist_on");
    $(".dist_on").not(this).attr("class", "dist_radio");
    console.log($(this).attr("class"));
});

or better using .addClass() and .removeClass() to make your code clearer:

$(".dist_radio").click(function () {
    $(".dist_radio").removeClass("dist_on");
    $(this).addClass("dist_on");
});

You can use .not() function to exclude the element from the selected set. Passing this to .not() will exclude the current object. You do not need if here to exclude it.

 $(".dist_on").not(this).attr("class", "dist_radio");

.not(): Remove elements from the set of matched elements.

Your code would be

$(".dist_radio").click(function() {
    $(this).attr("class", "dist_radio dist_on");
    $(".dist_on").not(this).attr("class", "dist_radio");
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top