Jquery按钮背景颜色交替

时间:2011-10-05 16:27:21

标签: jquery

我有一个foragainst按钮列表。我要做的是,如果单击for,则该行的against按钮具有替代颜色。我试过用jquery做这个,但它不起作用。我该如何解决?这是jsfiddle http://jsfiddle.net/mdanz/9H9qE/1/

    <style type="text/css">
.rate3 {
padding:5px;
font-family:Arial;
color:#FFFFFF;
cursor:pointer;
background-color:red;
border:1px solid #000000;
}

.rate4 {
padding:5px;
font-family:Arial;
color:#FFFFFF;
cursor:pointer;
background-color:red;
border:1px solid #000000;
}

.vote {
height:30px;
width:auto;
margin-bottom:10px;

}
</style>
<script type="text/javascript">
$('.rate3').live('click',function() {

    $(this).css('background-color','#FFFFFF');
        $(this).css('color','red');
        $(this).parent('div').next('.rate4').css('background-color','red');
        $(this).parent('div').next('.rate4').css('color','#FFFFFF');

}

$('.rate4').live('click',function() {

    $(this).css('background-color','#FFFFFF');
        $(this).css('color','red');
        $(this).parent('div').next('.rate3').css('background-color','red');
        $(this).parent('div').next('.rate3').css('color','#FFFFFF');

}
</script>
<?php for($i=0;$i<11;$i++) {  ?>
<div class="vote"><a class="rate3">For</a> <a class="rate4">Against</a></div>

<?php  } ?>

3 个答案:

答案 0 :(得分:2)

您不需要.live('click')因为您没有使用jQuery动态修改DOM,所以只需使用.click()

此代码应该有效:

$('.vote a').click(function() {
    $(this).siblings().css({
        backgroundColor: 'red',
        color: 'white'
    });
    $(this).css({
        backgroundColor: 'white',
        color: 'red'
    });
});

演示:http://jsfiddle.net/9H9qE/19/


但是我更喜欢用类来做这个,因为它更容易混乱样式表(更容易):

$('.vote a').click(function() {
    $(this).addClass('selected').siblings().removeClass('selected');
});

适当的CSS:

.selected {
    background-color: white;
    color: red;
}

演示:http://jsfiddle.net/9H9qE/22/

答案 1 :(得分:0)

尝试以下方法:

$('a').click(
    function(){
        if ($(this).is('.rate3')){
            c = '.rate4';
        }
        else {
            c = '.rate3';
        }

        $(this).closest('.vote').find(c).css({
            backgroundColor : '#fff'
        });
    });

JS Fiddle demo

答案 2 :(得分:0)

要添加Blender的答案,您还可以清理如何设置CSS属性,如下所示:

$(this).css({
    backgroundColor: 'white',
    color: 'red'
});

这是一个有效的example

相关问题