jQuery:是否可以在单击时更改无ID/无类元素

jQuery: is it possible to make ID/class-less elements change on click?

本文关键字:ID 元素 是否 单击 jQuery      更新时间:2023-09-26

示例 css:

div {
  background-color: green;
}

示例 html:

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

是否可以将 jquery 点击绑定到这些,以便点击的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的这个:揭秘 - 雷米夏普

使用这个

$("div").click(function() {
   // first change all to default color
   $('div').css( 'background-color', 'green');
$(this).css( 'background-color', 'blue');
alert($(this).text());
});

单击的元素将被$(this),因此$(this).css("background-color", "green");将为单击的元素着色,$("div").removeAttr("style")将从其余元素中删除所有定义的颜色。

所以:

$("div").click(function() {
    // remove the style attribute from every 'div' element to reset it to the value defined in CSS
    $("div").removeAttribute("style");
    // use $(this) to apply the color the clicked element itself
    $(this).css({"background-color": "green"});
});