gpt4 book ai didi

javascript - jQuery:是否可以在点击时更改 ID/无类元素?

转载 作者:行者123 更新时间:2023-11-30 08:01:27 24 4
gpt4 key购买 nike

示例 CSS:

div {
background-color: green;
}

示例 html:

<div>apple 1</div>
<div>apple 2</div>
<div>apple 3</div>

是否可以将 jquery clicks 绑定(bind)到这些,以便单击的 div 将背景颜色更改为蓝色,而其他的将恢复为默认颜色?

我在想:

$("div").click(function() {
// first change all to default color
$("div").each( background-color: green; }
// then change the clicked div to blue
how to get the clicked element in here I dont know.
});

最佳答案

使用$(this) 来引用被点击的元素:

    $("div").click(function() {
// first change all to default color
$("div").css('background-color', 'green')
// then change the clicked div to blue
$(this).css('background-color','blue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div>Apple 1</div>
<div>Apple 2</div>
<div>Apple 2</div>

进一步阅读:

JQuery's this: demystified - by Remy Sharp

关于javascript - jQuery:是否可以在点击时更改 ID/无类元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27018768/

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