[英]jQuery - Select children with $(this)
我嘗試使用jquery $(this)
選擇器和元素的類來計算div中的子節點數。 結果不同。 我認為jquery的$(this)
是指函數的所有者對象,是否有任何關於$(this)
的特殊內容我缺少什么?
$('.parent').ready(function(){
$('.parent').children().length; // 6
$(this).children().length; // 1
});
這個:
$('.parent').children().length; // 6
是正確的方法。 這個:
$(this).children().each(function().length; // 1
是語法錯誤。 如果你真的想要遍歷孩子,你可以使用“.each()”,但你必須正確地做到這一點:
$(this).children().each(function() {
var $child = $(this);
// ...
});
請注意,在“.each()”回調中, this
將連續引用每個子節點,因為jQuery調用了該函數。
$(this)
在$('.parent').ready()
方法引用$('.parent')
對象。
$(this)
在children()
集合的each()
方法內引用當前迭代的子節點。
因此,實現相同數量(無論出於何種原因)的方式是:
$('.parent').ready(function(){
var directLength = $(this).children().length; // 6
var indirectLength = 0;
$(this).children().each(function(){
indirectLength++;
});
alert([directLength, indirectLength].join("\n"));
});
編輯:您的評論只有一個含義:您有6個元素與parent
類,每個元素只有一個子元素。 所以我假設你想要計算父元素,這里是適當的代碼:
$(document).ready(function() {
var directLength = $('.parent').length; // 6
var indirectLength = 0;
$('.parent').each(function() {
indirectLength++;
});
alert([directLength, indirectLength].join("\n"));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.