2016-07-25 57 views
1

我有許多自動生成的表,並且這些表在thead中具有<span class="productNumber">元素,該元素顯示錶中的產品數量。 (現在這是通過<?php count($products); ?>在php中完成的)。jQuery:在動態創建的表中訪問類的單個實例

我寫了一個過濾器來幫助用戶瀏覽這些表格。該篩選器允許用戶選擇產品類別,並且所有沒有此產品類別的tr元素都獲得Bootstrap類hidden

我現在想用jQuery來計算每個表的實際可見元素並顯示實際可見的元素數。

我目前的做法是這樣的:

$('table').each(function(){ 
    let counter = 0; 
    $('tr', this).each(function(){ 
     if (this.hasClass("hidden")) { 
      counter++; 
     }; 
    }); 
    $('.productNumber').html(counter); 
}) 

的問題是,這將覆蓋所有.productNumber元素具有相同值(可見產品在最後table數)。

我試着用各種方式修改它($('.productNumber', this),$('.productNumber')[0]等),但是不能僅寫入當前的table.productNumber

+0

附註:您不需要calc下'counter',只是'$( 'tr.hidden',這一點).length'應該給你想要的號碼 –

回答

0

最簡單的方式做到這一點:

$("table").each(function(){ 
    var count = $(this).find("tr:not([class*='hidden'])").size(); 
    $(this).find(".productNumber").first().html(count); 
}); 

翻譯:

For each table: 
    Get the number of tr's that don't have "hidden" defined in 
    it's class attribute and assign to the count variable. 
    Find the first ".productNumber" cell in the table and set its 
    content 
0

使用這個選擇

$(this).children('.productNumber').html(counter); 
+1

應該用'find()', 'children()'只會得到直系後代。 – Tushar

+0

它是表的後代元素類。 –

+1

歡迎來到Stack Overflow!儘管這段代碼可以解決這個問題,但[包括一個解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ

0

我的概念證明。 https://jsfiddle.net/dewwwald/8gn5jdsL/1/

該問題通過將此指定給產品號查找來解決。假設productNumber位於tr內部,則爲 。也正如你描述你的要求,我讀this.hasClass("hidden")應該有一個!所以!this.hasClass("hidden")

$('table').each(function(){ 
    let _this = this; 
    _this.counter = 0; 
    $('tr', _this).each(function(){ 
    if (!this.hasClass("hidden")) { 
     _this.counter++; 
    }; 
    $('.productNumber', this).html(_this.counter); 
    }); 

}) 
相關問題