2012-06-23 39 views
2

我試圖做這樣的:如何將「this」用作選擇器的一部分?

$(this + ' li:not(:nth-last-child(2)):not(:last-child)').hide() 

完整的代碼示例:

$('.comments').each(function(){ 
    $(this + ' li:not(:nth-last-child(2)):not(:last-child)').hide() 
    var template = $('#expand').html(); 
    $(this).prepend(template) 
}); 

我需要運行它作爲一個「每個」功能全,因爲我想提出一個條件之後。

回答

4

嘗試

$('li:not(:nth-last-child(2)):not(:last-child)', this).hide(); 

docs

jQuery的(選擇器[,上下文])

選擇器 - 包含一個選擇器表達式

上下文中的串 - DOM元素,文檔或jQuery t Ø使用作爲上下文

所以,你可以使用this作爲上下文參數:

$('.comments').each(function(){ 
    $('li:not(:nth-last-child(2)):not(:last-child)', this).hide() 
    var template = $('#expand').html(); 
    $(this).prepend(template) 
}); 
+0

值得關注的是在幕後,所有的'$(選擇,背景)'所做的就是調用'$(上下文).find(選擇)':HTTP ://james.padolsey.com/jquery/#v=git&fn=jQuery.fn.init –

+0

是的,'$(selector,context)'調用'$(context).find(selector)',但是**作品**。我不明白你的意思是「值得注意」......? – Zbigniew

2

如果你想找到所有內thisli:not(:nth-last-child(2)):not(:last-child),你可以使用find()

$(this).find('li:not(:nth-last-child(2)):not(:last-child)').hide(); 

另外值得如果你知道你正在尋找的元素注意只打算是一個深層次,那麼你應該使用children()而不是find()

0

這是一個對象不是一個字符串,你可以以建立您需要選擇附加其他字符串。

只需使用find()遍歷代碼:

$('.comments').each(function(){ 
    $(this).find('li').not(':nth-last-child(2)').not(':last-child').hide(); 
    var template = $('#expand').html(); 
    $(this).prepend(template); 
});