如何获取每个tag
的背景色以使其与checkbox
的{{1}}相关联?
现在,它会更改所有标签的颜色。
data-color
$("input").on("click", function(e) {
var tagColor = $(this).attr("data-color");
var tag = `<output class='tag'></output>`;
if ($(this).is(".chk")) {
$(".chks").empty();
$(".chk:checked").each(function() {
$(tag)
.appendTo(".chks")
.attr("data-tag", $(this).val())
.css("background", tagColor)
.val($(this).val());
});
} else {
return false;
}
});
.selections {
border: 1px solid;
height: 50px;
display: flex;
align-items: center
}
.tags {
display: flex;
align-items: center
}
output.tag {
color: white;
border-radius: 9px;
margin: 0.3rem;
padding: 0.9rem;
}
答案 0 :(得分:2)
以下修改后的代码应该起作用
$("input").on("click", function(e) {
var container = $(".chks")
var tag = `<output class='tag'></output>`;
if ($(this).hasClass("chk")) {
container.empty()
$("input.chk:checked").each(function(index) {
var tagColor = $(this).attr("data-color");
$(tag)
.appendTo(container)
.attr("data-tag", $(this).val())
.css("background", tagColor)
.val($(this).val());
});
} else {
return false;
}
});
.selections {
border: 1px solid;
height: 50px;
display: flex;
align-items: center
}
.tags {
display: flex;
align-items: center
}
output.tag {
color: white;
border-radius: 9px;
margin: 0.3rem;
padding: 0.9rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='selections'>
<div class='tags chks'></div>
</div>
<div class="chkes">
<label><input data-color="purple" value="one" type="checkbox" data-type='one' class="chk">One</label>
<label><input data-color="orange" value="two" type="checkbox" data-type='two' class="chk">Two</label>
<label><input data-color="brown" value="three" type="checkbox" data-type='three' class="chk">Three</label>
</div>