gpt4 book ai didi

jquery - 如何合并这两个 jquery 函数来为 div 的背景着色?

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:28 25 4
gpt4 key购买 nike

当选中表中的复选框时,我想为 div 提供背景颜色。

这是 HTML:(影响div背景颜色的复选框)

<div id="main">
<div id="1"><input type="checkbox" value="1" name="" ></div>
<div id="1"><input type="checkbox" value="2" name="" ></div>
<div id="1"><input type="checkbox" value="3" name="" ></div>
<div id="1"><input type="checkbox" value="4" name="" ></div>
</div>

(表格中的复选框)

<table id="main1">
<tr>
<td><input type='checkbox' value="1" ></td>
</tr>
<tr>
<td><input type='checkbox' value="2" ></td>
</tr>
<tr>
<td><input type='checkbox' value="3" ></td>
</tr>
<tr>
<td><input type='checkbox' value="4" ></td>
</tr>
</table>

和 jQuery

(用于表格和 div 复选框的反之检查)

    $(function() {
var checkboxes = $(":checkbox").change(function() {
var value = $(this).val();
checkboxes.filter(function() {
return value == $(this).val()

}).not(this).prop('checked', this.checked);
});
});

(用于在选中 div 的复选框时为 div 提供背景颜色)

    $("#main input[type='checkbox']").on("change", function() {
var that = this;
// alert(that.value);
$(this).parent().css("background-color", function() {
return that.checked ? "rgb(251, 252, 170, 0.7)" : "";
});
});

最佳答案

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div id="main">
<div id="1"><input type="checkbox" value="1" name="">1</div>
<div id="1"><input type="checkbox" value="2" name="">2</div>
<div id="1"><input type="checkbox" value="3" name="">3</div>
<div id="1"><input type="checkbox" value="4" name="">4</div>
</div>


<table id="main1">
<tr>
<td><input type='checkbox' value="1">t1</td>
</tr>
<tr>
<td><input type='checkbox' value="2">t2</td>
</tr>
<tr>
<td><input type='checkbox' value="3">t3</td>
</tr>
<tr>
<td><input type='checkbox' value="4">t4</td>
</tr>
</table>
<script>
$(function() {
var checkboxes = $(":checkbox").change(function() {
var value = $(this).val();
var that = this;
if ($(this).parent()[0].nodeName !== "TD") {
$(this).parent().css("background-color", function() {
return that.checked ? "rgb(251, 252, 170, 0.7)" : "";
});
}

$("div input[value='" + value + "']").parent().css("background-color", function() {
return that.checked ? "rgb(251, 252, 170, 0.7)" : "";
});



checkboxes.filter(function() {
return value == $(this).val()

}).not(this).prop('checked', this.checked);
});
});
</script>

关于jquery - 如何合并这两个 jquery 函数来为 div 的背景着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50849217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com