2012-01-13 159 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