2012-09-28 22 views
2

如果找到超過3個td元素,並且不執行任何操作,則嘗試將HTML塊添加到表格中表中的元素少於3個。我已經循環遍歷表格,並且能夠檢查每個表格中有多少個tds。僅當HTML中的HTML數量超過X時纔將HTML添加到表格

我試過使用.filter();和$ .each(),但無法破解它。

因此:>>如何將HTML添加到傳遞if> 3語句的表中?

我仍在學習JavaScript和jQuery,請耐心等待。

這裏是迄今爲止代碼:

var tbls = $("body").find("table.responsive").length; 
var data = Array(); 

for(var index = 0; index < tbls; index++){ 
    $("table.responsive").each(function(i, v){ 
     data[i] = Array(); 
     $(this).find("td").each(function(ii, vv){ 
      data[i][ii] = $(this).text(); 
    }); 
    }) 
} 

data.forEach(function(item) { 
    if(item.length > 3) { 

     //here I want to add the HTML, but it is applied to all tables 
     $("table.responsive").before("<div style='position:relative;'><span class='MobiScroll'></span></div>"); 
    return false;   
    } 
});​ 

這裏是一個演示:http://jsfiddle.net/design4lifeblog/gSPXu/15/

+0

我想我需要學習 「這個」 了。謝謝大家的回覆。 – Tony

回答

1

你並不需要開始從身體穿越元素,使這個數組,可以算每個功能中的TD。

$("table.responsive").​each(function(){ 
    if ($('td', this).length > 3) { 
     $(this).before("<div style='position:relative;'><span class='MobiScroll'></span></div>"); 
    } 
})​ 
+1

_所有的人類行爲都有以下七個原因中的一個或多個:機會,自然,強迫,習慣,理性,激情,慾望。「Aristotle」 – undefined

+0

downvoter可以解釋downvote的原因嗎? –

+0

謝謝你的迅速回復,很好。我擔心這會很簡單! – Tony

0
$("table.responsive").each(function(){ 
    if($(this).find('td').size() > 3) 
    $(this).before("<div style='position:relative;'><span class='MobiScroll'></span></div>"); 
}) 

http://jsfiddle.net/pKWXZ/1/

1
$(function(){ 
    $("table.responsive").each(function(){ 
    if ($(this).find('td').length > 3) { 
     $(this).before("<div style='position:relative;'><span class='MobiScroll'></span></div>"); 
     //alert($(this)) 
    } 
})}); 

DEMO

+0

感謝您抽出時間,這似乎也很棒:) – Tony