我在 Drupal 中使用暴露的过滤器单选按钮,我注意到 html 结构使得在 :checked 时很难选择要更改的标签。
如果先输入 html 结构,然后输入标签,那么我可以使用“input[type=radio]:checked + label”选择标签,但是标签会环绕输入。
if (jQuery("input[type=radio]:checked")){
jQuery("input[type=radio]:checked .control-label").css("font-weight", "bold");
}
<body>
<label class="control-label" for="edit-tid-all">
<input class="bef-select-as-radios form-radio" type="radio" id="edit-tid-all" name="tid" value="All" checked="checked" style="font-weight: bold;">
Select all
</label>
<label class="control-label" for="edit-tid-all">
<input class="bef-select-as-radios form-radio" type="radio" id="edit-tid-all" name="tid" value="All" checked="checked" style="font-weight: bold;">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Selection 1
</label>
<label class="control-label" for="edit-tid-all">
<input class="bef-select-as-radios form-radio" type="radio" id="edit-tid-all" name="tid" value="All" checked="checked" style="font-weight: bold;">
Selection 2
</label>
我可以看到它在输入字段中添加了粗体字体,但这不是我想要的。我只希望它出现在已检查的标签上。有什么想法吗?
最佳答案
假设您希望在选择时将最接近所选单选按钮的标签设为粗体,那么您需要向输入本身添加一个事件处理程序。然后,您可以在添加类之前使用 closest()
获取label
。另请注意,您还需要从其他标签中删除该类。试试这个:
$('.bef-select-as-radios').change(function() {
$('label').removeClass('active');
$(this).closest('label').addClass('active');
}).filter(':checked').change();
label.active {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label class="control-label">
<input class="bef-select-as-radios form-radio" type="radio" name="tid" value="All" checked="true" />
Select all
</label>
<label class="control-label">
<input class="bef-select-as-radios form-radio" type="radio" name="tid" value="All" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Selection 1
</label>
<label class="control-label">
<input class="bef-select-as-radios form-radio" type="radio" name="tid" value="All" />
Selection 2
</label>
这里需要注意的一件事是,我从输入中删除了 id
属性,因为它们都是相同的,而它们必须是唯一的。这可能会导致一些意外的行为,所以我只是删除了它们。
关于javascript - 向上遍历 DOM 以选择包含在单选按钮输入中的标签(Drupal 公开的过滤器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49736377/