如何不首先启用切换类?

时间:2015-08-04 09:22:45

标签: javascript jquery html css

$(document).ready(function(){
  $("#summary").click(function(){
    $(this).toggleClass('clicked');
  });
});
.clicked {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        
<div id="summary">
  <div class="clicked">111</div>
  <div class="clicked">222</div>
</div>

如何在html页面加载时不将beckoned-color设置为红色。单击其div时只将其更改为红色?

4 个答案:

答案 0 :(得分:2)

从你的div中删除class="clicked"

$(document).ready(function(){
  $("#summary").click(function(){
    $(this).toggleClass('clicked');
  });
});
.clicked {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        
<div id="summary">
  <div>111</div>
  <div>222</div>
</div>

答案 1 :(得分:2)

您在加载页面时已将.clicked添加到div,而您想通过点击div来切换课程。请尝试以下代码:

&#13;
&#13;
$(function(){
  $(document).on('click', '#summary', function(){
    $(this).toggleClass('clicked');
  });
});
&#13;
.clicked {
  background-color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        
<div id="summary">
  <div class="someclass">111</div>
  <div class="someclass">222</div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

只需从div标记

中删除内联类clicked即可

HTML CODE:

<div id="summary">
  <div >111</div>
  <div >222</div>
</div>

现场演示@ JSFiddle:http://jsfiddle.net/dreamweiver/qjrahp6t/

答案 3 :(得分:0)

从HTML中删除类clicked。只有在点击后它才会变红。

<div id="summary">
  <div class="">111</div>
  <div class="">222</div>
</div>