2016-04-19 15 views
-1
<span class="help-block" style="color:red;text-align:left;" id="1012Error">Error Block</span> 
<span class="help-block" style="color:red;text-align:left;" id="1013">Clear</span> 
<span class="help-block" style="color:red;text-align:left;" id="1012Error">Error Block</span> 
<span class="help-block" style="color:red;text-align:left;" id="1012">Clear</span> 

想實現這樣的試圖找到如果某些字符存在於一個id

if(id contains "error") 
{ 
    $(this).html(""); 
} 

可以有人指導我如何得到這個

+0

你應該考慮使用除ID的部分以外的東西來指示錯誤狀態,就像一個類或數據屬性。 –

回答

2

jQuery的功能selectors that can be used to target specific elements based on their attributes。在這種情況下,您可以在這種情況下使用兩種方法。

的結束與選擇$=

你可以找到具有屬性的任何元素的最終使用$= attribute selector通過以下語法特定短語:

// This will empty the HTML for any element that has an ID that ends with "Error" 
$('[id$="Error"]').html(''); 

的包含選擇*=

類似地,*= attribute selector將會升發現,有一定的屬性,「包含」一個特定值的任何元素:通過each()

如果您需要執行多個操作爲您的元素

$('[id*="Error"]').html(''); 

處理多個操作,您可以使用each()功能遍歷這些結果和處理您的操作:

// Find each element that ends with "Error"... 
$('[id*="Error"]').each(function(){ 
    // And clear it out 
    $(this).html(''); 
    // Then do something else here 
}); 
0

你可以做這樣的事情

$('span.help-block').each(function(){ 
    var id = $(this).attr("id"); 
    # test if it matches error 
    if(id.match(/error/i)){ 
    # your operation here 
    $(this).text(""); // for example 
    } 
}) 
相關問題