jQuery 不会在 .each 函数之前删除 class

jQuery doesn't removing class before .each function

我的脚本有点小问题。

该脚本看起来有效,但每次它都会添加选定的 class。它会在 onclick 之前重置它,但 class 不会将其删除。可能是什么问题?

集合中 .payment class 中只有一个元素应该有 .selected class

$(".payment").each(function() { 
    $(".payment").removeClass("selected");
    $(this).on("click", function() { 
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true);
   });
});
.selected { 
background: #eaeaea;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="payment">
 <input type="radio" /> example
</div>

<div class="payment">
 <input type="radio" /> of my
</div>

<div class="payment">
 <input type="radio" /> problem
</div>

您只是在开头删除了 selected class。我假设您希望每次选中复选框时都将其删除,就像下面的代码一样。

$(".payment").each(function() { 

   $(this).on("click", function() { 
   $(".payment").removeClass("selected");
  $(this).addClass("selected");
  $(this).find('input[type="radio"]').prop("checked", true);
   });
});
.selected { 
background: #eaeaea;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="payment">
 <input type="radio" /> example
</div>

<div class="payment">
 <input type="radio" /> of my
</div>

<div class="payment">
 <input type="radio" /> problem
</div>

也许您应该修改代码以避免多个事件绑定。在循环中绑定事件不是一个好习惯。

    $(document).ready(function() {
        $(document).on("click", ".payment", function() {
            $(".payment.selected").removeClass("selected");
            $(this).addClass("selected");
            $(this).find('input[type="radio"]').prop("checked", true);
        });
    });

演示:http://jsfiddle.net/lotusgodkk/GCu2D/2237/

从所有 .payment 中删除 class 并为当前元素添加 class:

$(".payment").on("click", function() { 
    $(".payment").removeClass("selected");
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true)
});
.selected { 
background: #eaeaea;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="payment">
 <input type="radio" name="myRadio"/> example
</div>

<div class="payment">
 <input type="radio" name="myRadio"/> of my
</div>

<div class="payment">
 <input type="radio" name="myRadio"/> problem
</div>