.parent()。toggleClass无效

时间:2016-09-20 10:13:47

标签: javascript jquery css toggleclass

我在这里有一个小提琴:https://jsfiddle.net/qxnk05ua/2/

当我点击按钮时,我希望背景改变颜色,非常简单。为什么不起作用?

使用Javascript:

$(document).ready(function(){
  $('.block button').click(function(){
    $(this).parent().toggleClass('active');
  });
});

3 个答案:

答案 0 :(得分:1)

你错过了jQuery参考。在下面添加对您的代码的引用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

这是一个有效的demo

答案 1 :(得分:1)

答案 2 :(得分:0)

$(document).ready(function(){
  $('.block button').click(function(){
    $(this).parent().toggleClass('active');
  });
});
.block{
  width:200px;
  height:200px;
  background-color:#FFF;
}
.block.active{
  background-color:#333;
}

.block button{
  padding:5px;
  color:#333;
  width:100px;
  margin-left:calc(50% - 50px);
  margin-top:calc(50% - 20px);
  border:none;
  text-align:center;
  background-color:#FAC657;
  border-bottom:3px solid #CFA54A;
  cursor:pointer;
}
.block button:active{
  margin-top:calc(50% - 17px);
  border-bottom:none;
  outline:none;
  box-shadow:none;
  -moz-box-shadow:none;
  -webkit-box-shadow:none;
}
.block button:focus{
  outline:none;
  box-shadow:none;
  -moz-box-shadow:none;
  -webkit-box-shadow:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="block">
  <button>
    change color
  </button>
</div>