change background onclick with class

时间:2016-03-23 06:13:42

标签: javascript jquery

I have few buttons, all with same class='background'. Now I'm using this to change the background colour of button onclick.

<script>
$(document).ready(function(){
    $(".background").click(function(){
        $('.background').css('background','rgba(0,0,0,0.2)');
    });
});
</script>

But this is changing background of all the buttons. How can I change background of the button which is clicked. NOTE: I've to do this without using id

3 个答案:

答案 0 :(得分:2)

使用this对象。

$(document).ready(function(){
    $(".background").click(function(){
        $(this).css('background','rgba(0,0,0,0.2)');
    });
});

答案 1 :(得分:2)

在点击的事件中使用上下文this,仅定位当前点击的元素:

$(".background").click(function(){
    $(this).css('background','rgba(0,0,0,0.2)');
});

答案 2 :(得分:0)

希望这会有所帮助

$(document).ready(function(){
    $(".background").click(function(){
        $(".background").css('background',''); // Reset background color of other buttons
        $(this).css('background','rgba(0,0,0,0.2)'); // Set backgroundcolor of this button
    });
});

jsfiddle