使用jQuery定位与已检查单选按钮关联的div

时间:2016-11-03 09:44:53

标签: jquery html css

HTML

<div class="container">
   <div class="target"></div>
   <input type="radio">
</div>

<div class="container">
   <div class="target"></div>
   <input type="radio">
</div>

<div class="container">
   <div class="target"></div>
   <input type="radio">
</div>

CSS

.target {
   background-color: red;
}

.active {
   background-color: blue;
}

的jQuery

$(document).ready(function(){
   $('.target').each(function(){
      if ($('.container:has(input:radio:checked)')) {
      $(this).addClass('active');
   }
   });
});

以上内容将class active添加到所有.target div 。我需要它做的是添加active {{1与当前class 相关联的.target div

我尝试使用checked radio和其他各种事情,但我没有赢:-S

不确定我是否应该使用.each?

非常感谢帮助!

3 个答案:

答案 0 :(得分:0)

你可以这样做。

&#13;
&#13;
$(document).ready(function(){
   $('.container input[type="radio"]').on('change',function(){
     if($(this).is(':checked')){
       $('.target').removeClass('active');
       $(this).closest('.container').find('.target').addClass('active');
     }
     
   });
});
&#13;
.target {
   background-color: red;
    width: 20px;
    height: 20px;
}

.active {
   background-color: blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
   <div class="target"></div>
   <input type="radio" name="color">
</div>

<div class="container">
   <div class="target"></div>
   <input type="radio" name="color">
</div>

<div class="container">
   <div class="target"></div>
   <input type="radio" name="color">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试修改你的jQuery:

$(document).ready(function(){
   $("input[type='radio']:checked").each(function(){
      $(this).parent().find(".target").addClass("active");
   }
   });
});

答案 2 :(得分:0)

几乎就在那里。当您在git status On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: CMS/App_Data/CMS.mdf modified: CMS/App_Data/CMS_log.ldf modified: CMS/Areas/Admin/Controllers/CmsController.cs modified: CMS/Areas/Admin/Views/Cms/Index.cshtml modified: CMS/CMS.csproj modified: CMS/Content/Site.css modified: CMS/Models/Data/Db.cs Untracked files: (use "git add <file>..." to include in what will be committed) CMS/Areas/Admin/Controllers/ShopController.cs CMS/Areas/Admin/Views/Shop/ CMS/Content/img/ CMS/Models/Data/CategoryDTO.cs CMS/Models/ViewModels/CategoryVM.cs no changes added to commit (use "git add" and/or "git commit -a") 循环中选择$('。container')时,您正在选择所有容器。您只需要选择父容器。

each

或者,不是迭代$(document).ready(function(){ $('.target').each(function(i, targetEl){ var containerEl = $(targetEl).closest('.container'); $(targetEl).removeClass('active'); // cleanup first if (containerEl.has('input:radio:checked') { $(targetEl).addClass('active'); } }); });元素并为父母钓鱼,你可以像这样迭代父母:

.target