2017-05-23 33 views
0

如何提取TD的文本內容和每一個存儲到從包含以下內容的另一數組的數組:如何從數組中的元素中提取所有td的文本內容?

//create two element in the array, that store a string containing html code 

tablecontentArray[0] = "`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr><td>Fruit 1</td><td>Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr><td>Fruit 3</td><td>Fruit 4</td></tr></tbody>`" 

tablecontentArray[1] = "`<tbody><tr><th>Title 5</th><th>Title 6</th></tr><tr><td>Fruit 5</td><td>Fruit 6</td></tr><tr><th>Title 7</th><th>Title 8</th></tr><tr><td>Fruit 7</td><td>Fruit 8</td></tr></tbody>`" 

//loop to extract the td text content from the each element of the tableContentArray and store it into extractedTdArray 

    extractedTdArray = []; 

回答

0

var str = "`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr><td>Fruit 1</td><td>Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr><td>Fruit 3</td><td>Fruit 4</td></tr></tbody>`" 
 
var extractedTdArray = str.split("<td>") 
 
    .filter(function(v){ return v.indexOf('</td>') > -1}) 
 
    .map(function(value) { 
 
    return value.split("</td>")[0] 
 
    }) 
 
    console.log(extractedTdArray)

首先你分手了串入陣列由<td>

0:"`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr>" 
1:"Fruit 1</td>" 
2:"Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr>" 
3:"Fruit 3</td>" 
4:"Fruit 4</td></tr></tbody>`" 

然後,你有閉幕</td>filter

0:"Fruit 1</td>" 
1:"Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr>" 
2:"Fruit 3</td>" 
3:"Fruit 4</td></tr></tbody>`" 

然後你把它分解的元素由</td>並得到第一個元素。我們已經拆分了<td>,所以我們知道從一開始就是我們想要的信息</td>

["Fruit 1", "Fruit 2", "Fruit 3", "Fruit 4"]

+0

這太好了。但是如果td是不同的,例如可能包含和另一個? – smuhero

0

設置一個表和推

var extractedTdArray = [];// create result array 

// loop across html strings 
$.each(tablecontentArray, function (key, table) { 
    $('#table').html(table);//create html table 
     // loop across the created table td's 
     $.each($('#table').find('td'), function (key2, td) { 
      var tdVal=$(this).text();// td value 
      //push to array 
      extractedTdArray.push(tdVal); 
     }); 
    }); 
}); 

設置多個表和映射

// set tables 
$.each(tablecontentArray, function (key, table) { 
    $('#table' + key).html(table).addClass('table'); 
}); 

// map td 
var extractedTdArray = $('.table tr:has(td)').map(function (i, v) { 
    return $(this).text(); 
}).get(); 
+0

你介意說明你的代碼是幹什麼的嗎?這也有助於理解你是否也可以提供小提琴鏈接。 – smuhero

相關問題