2013-02-28 66 views

回答

1

下面是一個例子,它增加了一個isLastSibling方法來檢查一個元素是否是最後一個兄弟。

var cheerio = require('cheerio'), 
    $ = cheerio.load('<p><a>1</a><b>2</b><i>3</i></p>'), 
    $fn = Object.getPrototypeOf($()); 

$fn.isLastSibling = function() { 
    return this.parent().children().last()[0] === this[0]; 
}; 

console.log(
    $('a').isLastSibling(), 
    $('b').isLastSibling(), 
    $('i').isLastSibling() 
); 

你應該得到的輸出爲false false true因爲<a><b>元素是不是最後的兄弟姐妹,但<i>元素。

+0

事實上,'length'未來時,有0()和''length'時,它的最後一個孩子。我剛測試過。奇怪。你可否確認? – 2013-02-28 06:11:55

+0

你說得對,它沒有用。我用一個完整的,經過測試的例子修改了我的答案。 – 2013-02-28 06:31:02

+0

謝謝。這樣可行。 – 2013-02-28 06:39:08

0

嘗試

<script type="text/javascript"> 

    $(function() 
    { 
     $('dom').each(function() 
     { 
      var $this = $(this); 
      if ($this === $this.parent().last()) 
      { 
       alert('got me!'); 
      } 
     }) 
    }); 

</script> 
+0

last()由於某種原因在cheerio中不起作用。它給了我整個父節點,而不是真正的最後一個:( – 2013-02-28 06:22:20

+0

.last()將選擇cheerio對象的最後一個元素 – 2013-02-28 06:25:03

0

檢查它使用的是jquery version

您可以使用last-child-selector這個

例如: $("div span:last-child").css('background','red');

這裏是文檔http://api.jquery.com/last-child-selector/

+0

我在這裏得到了最新的,它不使用jQuery(我相信):https ://github.com/MatthewMueller/cheerio。'div span:last-child' does not work because the other''non-span' elements in the'parent' that might last last child。 – 2013-02-28 06:31:22