删除类并在单击元素时添加类

时间:2015-02-21 13:04:53

标签: javascript jquery

jQuery已经在工作了,我想要实现的是标题 点击我想删除i标签的类,这是fa-to-off-off 并用fa-to-turn替换它。我已经实现了这个问题 所有的i标签都受到影响。

 <div class="row package-row">
      <div class="global-switch">
            <input type="checkbox" id="switch1" name="switch1" class="switch" />
            <label for="switch1">Hide Packages</label>
      </div><!--end of global-switch-->
      <div class="col-md-12">
            <div class="header-details">
                   <h3 id="toggle-h3-package"><i class="fa fa-toggle-off" style="margin-right: 10px;"></i>TITLE</h3>
                   <p>DESCRIPTION</p>
            </div>
            <div class="global-control" id="global-control">
                   CONTENT
            </div>
      </div>            
</div>

的jQuery

$('.toggle-h3-package').click(function(){
                $(this).parent().next('.global-control').animate({
                    height:'toggle',
                    opacity:'toggle'
                },{
                    duration: 5000,
                    specialEasing: {
                      width: "linear",
                      height: "easeOutBounce"
                    }
                });
            });
            $('.toggle-h3-package').click(function() {
                var target = $('.header-details .toggle-h3-package i');

                if (target.hasClass('fa-toggle-off')) {
                    $('.header-details .toggle-h3-package i').removeClass('fa-toggle-off').addClass('fa-toggle-on');
                }
                else {
                   $('.header-details .toggle-h3-package i').removeClass('fa-toggle-on').addClass('fa-toggle-off');
                }
            });

2 个答案:

答案 0 :(得分:0)

你应该缩小你的选择器:

var target = $('.header-details .toggle-h3-package i'); - 这将在页面上找到所有i个元素。而且您只需点击i中的.toggle-h3-package即可。将find方法与this

一起使用
$('.toggle-h3-package').click(function() {
    var target = $( this ).find( 'i' );
    // your code here

此外,您可以使用toggleClass函数,而无需检查元素是否包含某个类:

target.toggleClass('fa-toggle-on fa-toggle-off');

答案 1 :(得分:0)

  

这就是我所建议的......

 $('.toggle-h3-package').click(function() {
                    var target = $( this ).find( 'i' );
                        target.toggleClass('fa-toggle-on fa-toggle-off');
                });