2012-07-29 47 views
1

我正在嘗試編寫一個通用JavaScript,在從「展開」到「隱藏」單擊時可以重命名可摺疊鏈接,反之亦然。Twitter引導的通用JavaScript摺疊功能

我寫的,在jQuery的下面的代碼:

$(".collapse").collapse(); 

$(".collapse").on('show', function() { 
    $("a[data-target='#"+$(this).attr('id')+"']").text($("a[data-target='#"+$(this).attr('id')+"']").attr('data-on-hidden')) 
}); 
$(".collapse").on('hidden', function() { 
    $("a[data-target='#"+$(this).attr('id')+"']").text($("a[data-target='#"+$(this).attr('id')+"']").attr('data-on-active')) 
}); 

與下面的HTML交互:

<div class="collapse in" id="collapse-fields"> 
Expandable content 
</div> 
<a href="#" data-toggle="collapse" data-target="#collapse-fields" 
     data-on-hidden="Hide" data-on-active="Expand">Expand</a> 

我是新來的jQuery,我在想,如果我的代碼是寫在一個正確的方式,還是有更好的方法來編寫這樣的功能?

回答

2

既然你正在尋找一個通用的解決方案,這應該在任何地方工作:Demo (jsfiddle)

var $togglers = $('[data-toggle="collapse"]'); // Elements that toggle a collapsible 
$togglers.each(function() {      // Do the same thing for all elements 
    var $this = $(this); 
    var $collapsible = $($this.data('target')); // Collapsibles of this iteration 
    $collapsible.on('hidden', function() { 
     var text = $this.data('on-hidden');  // Get the data-on-hidden attribute value 
     text && $this.text(text);     // If it has text to replace, change it 
    }).on('shown', function() { 
     var text = $this.data('on-active');  // Get the data-on-active attribute value 
     text && $this.text(text);     // If it has text to replace, change it 
    }); 
}); 

你只需要在data-on-hiddendata-on-active屬性添加到該切換一個可摺疊的任何元素

注:我把切換屬性值的自由,使上隱藏對應時,它的隱藏和上活躍當它是可見的。