2011-10-28 13 views
0

我有一個帶有表單模塊的CMS,它會生成一個糟糕的標記,這使得樣式絕對不可能。表單對象和元素嵌套在不合要求的表,行和單元格中。檢查元素是否包含一個字符串,而不是一個字符串 - 也許是正則表達式

我正在通過javascript過濾掉所有需要的元素,並將它們放入一個數組中,並使用這些元素創建新的前端開發友好標記。

輸入字段,圖例和字段集沒有問題 - 但我的標籤過濾出現問題。我的標籤要麼像這樣包裝:<tr><td>Label</td></tr><tr><td><b>Label</b></td></tr> - 我需要過濾出來,並將它們放入一個數組中。

有沒有更簡單的方法來檢查,如果我的td包含純字符串,而不是輸入或其他html元素,而不是使用正則表達式?

var regex = new RegExp(???); 
jQuery("td").each(function() { 
    if(jQuery(this).has("b") || regex.test(jQuery(this).text())) 
    { 
     // Do stuff here 
    } 
} 

在此先感謝

回答

2

這將返回所有TD的的,要麼有沒有孩子或者有一個孩子是一個大膽的標籤。

$('td').filter(function() { 
    var children = $(this).children(); 
    return children.length == 0 
       || (children.length == 1 && children.first().is('b')) 
}); 

http://jsfiddle.net/t9bMG/

如果你想只返回實際上有文字,你可以使用這個元素:

$('td').filter(function() { 
    var t = $(this), children = t.children(); 
    return t.text().length > 0 
       && (children.length == 0 
        || (children.length == 1 && children.first().is('b'))) 
}) 

http://jsfiddle.net/t9bMG/1/

+0

我也有很多td沒有孩子,也沒有字符串,所以我仍然需要確保td實際上包含一個字符串。 – MadsMadsDk

+0

看我的編輯。你想要第二個例子。 –

+0

這也適用,也是一個可以接受的答案,但正則表達式更簡單,我認爲。雖然謝謝! :) – MadsMadsDk

2

你可以試試這個正則表達式

var regex = new RegExp('^[^<]*$')

如果在td文本中沒有任何開放的html標籤,則會匹配。如果您不想匹配空字符串,則使用+而不是*

說明

 
"^" +  // Assert position at the beginning of the string 
"[^<]" + // Match any character that is NOT a 「<」 
    "*" +  // Between zero and unlimited times, as many times as possible 
"$"   // Assert position at the end of the string 
+0

我會嘗試這種方法 - 它似乎更簡單,正是我所期待的。 – MadsMadsDk

相關問題