Jquery 委托事件仅在两个选择器之一上工作

Jquery Delegate event working on one of the two selectors only

本文关键字:选择器 两个 工作 事件 Jquery      更新时间:2023-09-26
$("body").on("change", "input[type='checkbox'],input[type=radio]", function(event){
  $("input[type='checkbox']").on('change',function() {
    var that = this;
    if (!$(this).parent().hasClass("remember-label")){
      $(this).parent().css("background-color", function() {
          return that.checked ? "#C0E9F7" : "";
      });
    }
  });
  $("input[type=radio]").on('click',function() {
    $(this).parents().eq(1).siblings().css("backgroundColor","");
    $(this).parents().eq(1).css("backgroundColor","#C0E9F7");
  });
});

虽然我想这应该有效,但它仅适用于单选按钮。由于每次内容动态更改时,我都必须放置两个选择器,因为有时单选按钮会添加到 DOM 中,有时还会添加复选框。

问题是输入的单击区域变得不可单击,除非您明确单击复选框或单选按钮而不是覆盖整个区域的标签。

这是HTML(它有轨道,但你可以理解结构)

<label for="choice_<%= choice.id %>">
            <%= radio_button_tag("choice","#{choice.id}",false,class:"radio big-radio") %>
            <% if choice.image? %>
              <%= image_tag rewrite_url(choice.image_url(:resized)), class:"choice-image" %>
            <% else %>
              <%= choice.description %>
            <% end %>
          </label>

该代码适用于单选按钮,但同样适用于复选框。

为什么

你需要在事件处理程序中使用事件处理程序..简单地你可以像这样使用它

$(document).ready(function(){ 
     $("body").on("change", "input[type='checkbox']",function() {
        var that = this;
        if (!$(this).parent().hasClass("remember-label")){
          $(this).parent().css("background-color", function() {
              return that.checked ? "#C0E9F7" : "";
          });
        }
    });
    $("body").on("click", "input[type=radio]" ,function() {
      $(this).parents().eq(1).siblings().css("backgroundColor","");
      $(this).parents().eq(1).css("backgroundColor","#C0E9F7");
    });
});

注意:请确保包含 jquery

您应该只绑定一次:

$("body").on("change", "input[type='checkbox'],input[type=radio]", function(event){
     // here you can check if this is check box or radio
        if($(this).is(":checkbox")) {
            // do this
        }else{
           // do for radios
        }
 });