gpt4 book ai didi

jquery li和checkbox的背景颜色

转载 作者:行者123 更新时间:2023-12-01 03:03:15 25 4
gpt4 key购买 nike

我想更改单击时要更改的 li 元素的背景颜色。因此,当用户单击第一个 li 时,背景颜色应为红色,当用户单击第二个 li 时,第二个应变为红色,但第一个应变为白色。

简而言之,应更改所选 li 的背景颜色以显示其突出显示。

此外,还应仅选中选定的 li 的复选框。我尝试过像下面这样做。但对于所有选定的李来说,情况正在发生变化。请帮忙。

<html>
<head>
<script type="text/javascript" src="http://editor.webyana.com/javascripts/client_scripts/potential/jquery.js"></script>
<script>
$(document).ready(function () {
$("li.gc").click(function () {

$("li.gc").each(function (i) {
$("li.gc[i]").css({
backgroundColor: '#FFA700'
});
});
$(this).css({
backgroundColor: '#000000'
});

$(this).children("input[type=checkbox]").attr('checked', 'checked');

//do something with the sortcat
});

});
</script>
</head>
<body>
<ul>
<li class="gc">
<input type="checkbox" />
Check1
<a>Link1</a>
</li>
<li class="gc">
<div>
<input type="checkbox" />
Check2
<a>Link2</a>
</div>
</li>
<li class="gc">
<div>
<input type="checkbox" />
Check3 Link3
</div>
</li>
<li class="gc">
<div>
<input type="checkbox" />
Check4 Link4
</div>
</li>
</ul>
</body>

</html>

最佳答案

我建议您不要使用 css 函数,而是使用 CSS 中的类并稍微简化逻辑。请参阅this fiddle .

// store this for later use. only search once!
var items = $("li.gc");

items.click(function() {
// again, only need to run this once - cache the selector!
var item = $(this);
// remove the selected class and uncheck all the inputs for all items
items.removeClass("selected").find("input").removeAttr("checked");
// add the selected class and check the input
item.addClass("selected").find("input").attr('checked', 'checked');
});
<小时/>

仅供您引用,这是您最初的代码想法(使用 .css())扩展:

$("li.gc").click(function () {
$("li.gc").css({
backgroundColor: '#FFA700'
});
$(this).css({
backgroundColor: '#000000'
});

$(this).children("input[type=checkbox]").attr('checked', 'checked');

//do something with the sortcat
});

当您使用 .css() 作为 setter 时,它会对所有匹配的项目进行操作。

关于jquery li和checkbox的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6000851/

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