2012-01-13 157 views
0

我无法让Jquery .closest()正常工作。无法让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> 

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

+0

确保你结束你的jQuery语句用';' – Mathletics 2012-01-13 19:54:26

+0

并请出示您的标记;我们无法验证您的选择器/遍历而不看到标记! – Mathletics 2012-01-13 19:55:07

+0

更多的可能是'.more-content'不是锚标签的祖先,因为如果锚标签是可见的,它必须是可见的。 '.closest'只用于选择祖先,而不是兄弟姐妹。请阅读文档http://api.jquery.com/closest/ – 2012-01-13 19:59:01

回答

2

如果传入show方法的a变量是.more元素,那么您希望使用选择同级元素而不是祖先元素。

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/

+0

我需要将最接近的同胞作为目标$'(a)'是 – Nasir 2012-01-13 20:05:47

+0

我是' ve已经尝试过'.prev()',但是如果两个'.more-content'同时打开,会导致冲突。 – Nasir 2012-01-13 20:08:27

+0

@Nasir'.more-content'是'.more'元素的上一个邻接的同胞,所以使用'.prev('。more-content')'可以正常工作。看看这个演示:http://jsfiddle.net/At3bL/1/ – Jasper 2012-01-13 20:08:52