我怎样才能将css类添加到使用jQuery单击的h3标记中

时间:2017-12-15 05:19:08

标签: javascript jquery

<li>
  <div id="lineop1"><a href="php/fabric/process1.php"><h3>Softshell</h3></a></div>
</li>
<li>
  <div id="lineop1"><a href="php/fabric/process1.php"><h3>Option</h3></a></div>
</li>
<li>
  <div id="lineop1"><a href="php/fabric/process1.php"><h3>Option 1</h3></a></div>
</li>

我需要显示点击了哪个h3标记以显示活动

2 个答案:

答案 0 :(得分:2)

你需要像下面这样做: -

$(document).ready(function(){
  $('.lineop1 a h3').click(function(e){
      e.preventDefault(); // to prevent page refresh with new url
      $('h3').removeClass('active'); // remove active class from other h3 tag
      $(this).addClass('active'); // add active class to current clicked tag
  });
});
.active{
  color:green;
  font-size:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
  <div class="lineop1"><a href="php/fabric/process1.php"><h3>Softshell</h3></a></div>
</li>
<li>
  <div class="lineop1"><a href="php/fabric/process1.php"><h3>Option</h3></a></div>
</li>
<li>
  <div class="lineop1"><a href="php/fabric/process1.php"><h3>Option 1</h3></a></div>
</li>

注意: - id每个元素都必须是唯一的。所以将id转换为class

周围的<div's>

如果您在页面刷新后点击h3后想要,那么相应的h3标记也有活动类,那么您必须使用{{1} }概念如下: -

jQuery的: -

localstorage

HTML: -

$(document).ready(function(){
    $('ul li').eq( localStorage.parent ).find('h3').addClass('active');
    $('.lineop1 a h3').click(function(e){
        var pagename = $(location).attr("href").split('/').pop();
        localStorage.parent=$(this).closest('li').index();
    });
});

我已经在我的本地主机上测试了它并且工作得非常好。

答案 1 :(得分:1)

h3添加点击处理程序。向其添加课程active

&#13;
&#13;
$(document).ready(function(){
    $(document).on('click','h3',function(){
        $('h3').removeClass('active');
        $(this).addClass('active');
    });
});
&#13;
.active{
   color:#ff00eb;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li>
  <div id="lineop1"><a href="#"><h3>Softshell</h3></a></div>
</li>
<li>
  <div id="lineop1"><a href="#"><h3>Option</h3></a></div>
</li>
<li>
  <div id="lineop1"><a href="#"><h3>Option 1</h3></a></div>
</li>
&#13;
&#13;
&#13;

修改:将点击事件附加到最近的唯一父元素是一种很好的做法。所以我加入了$(document).On

点击此链接查看Direct Vs Deletegated Events

的工作情况