通过jQuery切换按钮状态

时间:2018-04-28 18:41:05

标签: javascript jquery css

我有两个按钮,如(竖起大拇指)而不像(竖起大拇指)。单击一个按钮应切换两者的状态,只有一个处于活动状态。

以下是我到目前为止的尝试:

<button type="button" class="bout unlike bthumb boutontagthumbdown" id="unlike_'.$row['tag_number_id'].'" value="unlike">
    <i class="fas fa-thumbs-down fa-lg"></i>
</button>'
<button type="button" class="bout like bthumb boutontagthumbup" id="like_'.$row['tag_number_id'].'" value="like">
    <i class="fas fa-thumbs-up fa-lg"></i>
</button>

<script type="text/javascript">
    $(function(){
        console.log( "ready!" );

        $(".bout").click(function(){
            var Id = this.id;
            var Idunlike = ("#" + Id + ".bout.unlike");
            var Idlike = ("#" + Id + ".bout.like");

            if ( $(this).attr("value") == 'unlike' ){
                $(Idunlike).toggleClass("boutontagthumbdownclic");
                $(Idlike).addClass("boutontagthumbupclicreturn");
                console.log(Idunlike);
            } else if ( $(this).attr("value") == 'like' ) {
                $(Idlike).toggleClass("boutontagthumbupclic");
                $(Idunlike).addClass("boutontagthumbdownclicreturn");
                console.log(Idlike);
            }
        });
    });
</script>

2 个答案:

答案 0 :(得分:0)

以下内容应该有效:

XmlReader

<强> HTML:

$(function(){    
    $(".status button").click(function () {
        $(".status").find(".active").removeClass("active");
        $(this).addClass("active");
    })
});

CSS:

<div class="status">
    <button type="button" class="like" value="like">
        <i class="fas fa-thumbs-up fa-lg"></i>
    </button>'
    <button type="button" class="unlike" value="like">
        <i class="fas fa-thumbs-down fa-lg"></i>
    </button>'
</div>

答案 1 :(得分:0)

试试这个

$(function(){	
	
	$(".bout").click(function(){
		var id = $(this).attr('id').split('_')[1];		
		switch($(this).attr('value')){
			case 'like' :
				$('#like_'+id).addClass('boutontagthumbupclic').removeClass('boutontagthumbupclicreturn');
				$('#unlike_'+id).addClass('boutontagthumbdownclicreturn').removeClass('boutontagthumbdownclic');
			break;
			case 'unlike' :
				$('#like_'+id).addClass('boutontagthumbupclicreturn').removeClass('boutontagthumbupclic');
				$('#unlike_'+id).addClass('boutontagthumbdownclic').removeClass('boutontagthumbdownclicreturn');
			break;
		}
	});	
	
});
.boutontagthumbupclic{color:green;}
.boutontagthumbdownclic{color:red;}

.boutontagthumbdownclicreturn,
.boutontagthumbupclicreturn{color:#555;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<button type="button" class="bout unlike bthumb boutontagthumbdown" id="unlike_1" value="unlike"><i class="fa fa-thumbs-down fa-lg"></i></button>
<button type="button" class="bout like bthumb boutontagthumbup" id="like_1" value="like"><i class="fa fa-thumbs-up fa-lg"></i></button>