html5 - javascript/jquery高手请进!点击radio按钮更换div border 颜色失效
本文介绍了html5 - javascript/jquery高手请进!点击radio按钮更换div border 颜色失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
目前,我的代码可以用在单个 radio group. 如果是多个就出现问题。 点击第二排Zzz的时候,就连上面那排的红色边框也不见了。。。
大神们!请问哪里出错了?
html
<label style="width:100%"><div class="discount"><input type="radio" name="abc" checked>Apple</div></label>
<label style="width:100%"><div class="discount"><input type="radio" name="abc">Banana</div></label>
<label style="width:100%"><div class="discount2"><input type="radio" name="efg" checked>Milk</div></label>
<label style="width:100%"><div class="discount2"><input type="radio" name="efg">Zzz</div></label>
<label style="width:100%"><div class="discount2"><input type="radio" name="efg">Bbb</div></label>
css
.discount{
border: 2px solid #cccccc;
padding:2px;
padding:10px;
width:100%;
text-align:center;
border-radius: 5px;
}
.discount.checked {
border-color: red;
}
.discount2{
border: 2px solid #cccccc;
padding:2px;
padding:10px;
width:100%;
text-align:center;
border-radius: 5px;
}
.discount2.checked {
border-color: red;
}
jquery
<script>
$(":radio:checked").closest(".discount").addClass("checked");
$(":radio").on("change", e => {
const $div = $(e.target).closest(".discount");
console.log($div);
$(".discount").removeClass("checked");
$div.addClass("checked");
});
$(":radio:checked").closest(".discount2").addClass("checked");
$(":radio").on("change", e => {
const $div = $(e.target).closest(".discount2");
console.log($div);
$(".discount2").removeClass("checked");
$div.addClass("checked");
});
</script>
解决方案
我就喜欢这种有代码的问题
示例在这里,综合之前的回答
https://jsfiddle.net/7y2hw7L8/
代码有些改动,照例是用的 es6 的语法
$(":radio:checked").closest(".discount").addClass("checked");
$(":radio").on("change", e => {
const $radio = $(e.target);
const $div = $radio.closest(".discount");
// 找到当前 radio 的 name,下面用这个 name 来选 .discount
const name = $radio.attr("name");
$(`.discount:has([name=${name}])`).removeClass("checked");
$div.addClass("checked");
});
$(":radio:checked").closest(".discount").addClass("checked");
这篇关于html5 - javascript/jquery高手请进!点击radio按钮更换div border 颜色失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文