jQuery:是否可以在点击时更改ID / class-less元素?

时间:2014-11-19 14:00:29

标签: javascript jquery

示例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.
});

3 个答案:

答案 0 :(得分:4)

使用$(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

答案 1 :(得分:2)

使用此

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

答案 2 :(得分:0)

点击的元素将为$(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"});
});