jquery按钮颜色开关不起作用

标签 jquery

我尝试使用 addClass()removeClass()hasClass() 方法。但是这个小代码根本不起作用?

查看了所有 3 个函数的文档。看来应该可以。

<!DOCTYPE html>
<html>
<head>
<title>Trials</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
    .liked
    {
        color:red;
    }
</style>
</head>
<body>
<br><br><br>
<button id="like1" class="btn likeBtns liked">5<span class="glyphicon glyphicon-heart"></span></button>

<script>
$('.likeBtns').on('click', function(){

    var x = $(this).attr('id');
    x = "#"+x;
    if($("#like1").hasClass("liked"))
    {
        console.log("has");
        $("#like1").removeClass("liked");
    }
    else
    {
        console.log("doesnt have");
        $("#like1").addClass("liked");
    }
});
</script>
</body>
</html>

最佳答案

使用 toggleClass() 如下所示:-

工作示例:-

$('.likeBtns').on('click', function(){
  $(this).toggleClass("liked");
});
.liked{
  color:red;
}

.liked:hover,
.liked:focus,
.liked.focus {
    color:red !important;
}
<html>
  <head>
    <title>Trials</title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </head>
  <body>
    <br><br><br>
    <button id="like1" class="btn likeBtns">5<span class="glyphicon glyphicon-heart"></span></button>
  </body>
</html>

注意:- 点击按钮后点击外部即可显示效果。

这是因为您的 bootstrap.css 已在按钮上应用了以下 css:-

btn.focus, .btn:focus, .btn:hover {
    color: #333;
    text-decoration: none;
}

在我的代码中,我覆盖了 bootstrap 的 css 代码。现在它可以正常工作了

关于jquery按钮颜色开关不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43418461/

相关文章:

javascript - 如何设计点击面板如下链接和图片

javascript - 如何在javascript中读取json响应

javascript - 将页面分成两部分并向相反方向滚动两部分

javascript - 使用php存储提交信息并在单独的html页面上显示

javascript - tinyMCE 选项

jquery - 背景图像循环 - 具有平滑淡入淡出或过渡的 z 索引

javascript - 未捕获的类型错误 :JavaScript

jquery - 搞乱 IE 中的阴影

javascript - 下拉列表的选定项目在同一页面上显示文本

javascript - 使用选项卡时调整图表高度大小