2014-10-09 133 views
-1

HTMLjQuery的 - 添加/删除类

<div class="show-content-1 hidden"> 
    content 1 
</div> 

<div class="show-content-2 hidden"> 
    content 2 
</div> 

<div class="show-content-3 hidden"> 
    content 3 
</div> 

<div class="switch-content"> 
    <a id="content-1" href="#">link 1</a> 
    <a id="content-2" href="#">link 2</a> 
    <a id="content-3" href="#">link 3</a> 
</div> 

jQuery的

$('.switch-content a').on("click", function(e) { 
    e.preventDefault(); 
    var $this = $(this), 
     $id = $this.attr('id'), 
     $class = '.' + $('.show-' + $id).attr('class').replace('hidden', ''); 

    $('.show-' + $id).removeClass('hidden'); 
    $('.show-' + $id).addClass('animated fadeIn'); 
    $('div[class*=show]').not($class).addClass('hidden'); 
    $('div[class*=show]').not($class).removeClass('animated fadeIn'); 
});  

CSS

.hidden {display:none} 

使用上面的代码,如果我点击链接2,内容2将显示 - 这很好。

但再次单击链接2将隐藏内容2并且不会显示任何内容。有没有办法阻止第二次点击或继续显示内容2无论点击链接2多少次?

+0

似乎是工作罚款:[**的jsfiddle **](HTTP://的jsfiddle .net/5e878ccx /) – urbz 2014-10-09 14:42:04

+1

偏题:如果你的变量不是jQuery对象,你不应该用'$'来加前缀。你应该只为jQuery对象保留这个前缀。 – laruiss 2014-10-09 14:46:54

回答

0

您可以使用“数据”来防止再次点击。

$('.switch-content a').on("click", function(e) { 
    e.preventDefault(); 

    if ($(this).data('clicked')) return; 

    var $this = $(this), 
     $id = $this.attr('id'), 
     $class = '.' + $('.show-' + $id).attr('class').replace('hidden', ''); 

    $('.show-' + $id).removeClass('hidden'); 
    $('.show-' + $id).addClass('animated fadeIn'); 
    $('div[class*=show]').not($class).addClass('hidden'); 
    $('div[class*=show]').not($class).removeClass('animated fadeIn'); 

    $(this).data('clicked', true); 
}); 
+0

这样可以防止在第一次点击后进一步点击另一个链接。 – urbz 2014-10-09 14:44:23

+0

更新了我的答案。 – Wouter0100 2014-10-09 14:46:12

0

我会用一个jQuery对象,而不是它的类,以避免任何问题:

$('.switch-content a').on("click", function(e) { 
    e.preventDefault(); 
    var $content = $('.show-' + $(this).attr('id')); 

    $content.removeClass('hidden').addClass('animated fadeIn'); 
    $('div[class^=show]').not($content).addClass('hidden').removeClass('animated fadeIn'); 
});  
1

检查,看是否有内容的hidden类,如果它不要去碰它:

$('.switch-content a').on("click", function(e) { 
    e.preventDefault(); 
    var $this = $(this), 
     id = $this.attr('id'), 
     $content = $('.show-' + id); 

    if (!$content.hasClass('hidden')) return; 

    $content.removeClass('hidden').addClass('animated fadeIn'); 
    $('div[class*=show]').not($content).addClass('hidden'); 
    $('div[class*=show]').not($content).removeClass('animated fadeIn'); 
}); 

http://jsfiddle.net/nrtxtufz/

+0

,你也可以使用toogleClass('隐藏') – Balder 2014-10-09 14:47:50

+0

@Balder True ......尽管''切换];) – 2014-10-09 14:50:37