无法让Jquery .closest()工作?

时间:2012-01-13 19:53:09

标签: jquery

我无法让Jquery .closest()工作。

这是我的代码,它很简单,我看不出它为什么不起作用的原因:

Jquery的

show:function(a,fx){
        $('.more-content').hide();

        $(a).toggle(function() {
                t = $(this).closest(".more-content")
                if (fx.match('show')) {
                    t.show()
                };
                if (fx.match('slide')) {
                    t.slideDown()
                };
                if (fx.match('fade')) {
                    t.fadeIn()
                };
                $(this).html('Less')
            }, function() {
                if (fx.match('show')) {
                    t.hide()
                };
                if (fx.match('slide')) {
                    t.slideUp()
                };
                if (fx.match('fade')) {
                    t.fadeOut()
                };
                $(this).html('More')
            });
        } 

HTML

    <p><strong class="goal">The Goal</strong><br />
    To support those who are NEET <span class="more-content">We do this by providing education or training to enable said people to be...</span>
    <span class="more">More</span>

    <br /><br />
    To build community cohesion in the local area. <span class="more-content">This will lead to a community where people have the opportunity...</span> 
    <span class="more">More</span>
    </p>

感到困惑,所以非常感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:2)

如果传递给a方法的show变量是.more元素,那么您要使用select a sibling元素,而不是祖先元素。

var t = $(this).prev(".more-content");

此外,您正在创建一个全局变量(t)来保存切换功能的当前元素,但这不是一个好方法。只需在两个函数中选择正确的t元素:

var fx ='slide';

$(a).toggle(function() {
    var t = $(this).prev(".more-content");

    if (fx.match('show')) {
        console.log('1');
        t.show();
    };
    if (fx.match('slide')) {
        console.log('2');
        t.slideDown();
    };
    if (fx.match('fade')) {
        console.log('3');
        t.fadeIn();
    };
    $(this).html('Less')
}, function() {
    var t = $(this).prev(".more-content");
    if (fx.match('show')) {
        t.hide()
    };
    if (fx.match('slide')) {
        t.slideUp()
    };
    if (fx.match('fade')) {
        t.fadeOut()
    };
    $(this).html('More')
});

以下是演示:http://jsfiddle.net/At3bL/1/

相关问题