1

我正在尝试编写一个通用的 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 新手,我想知道我的代码是否以正确的方式编写,或者是否有更好的方法来编写这样的函数?

4

1 回答 1

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-hiddenanddata-on-active属性添加到任何切换可折叠的元素

注意:我冒昧地切换了属性的值,以便隐藏对应于隐藏时和活动时可见。

于 2012-07-29T21:27:32.077 回答