2014-08-31 27 views
0

如何獲得的jQuery 我想在(HREF)(ID)(跨度)如何通過jQuery的

之間的匹配(ID)來獲取匹配ID如果代碼 這裏

HTML

<table> 
<tr> 
<td class='zero'> 
    <span> 
    <a href="http//google&id=222.com">123</a> 
    <a>hgi</a> 
    </span> 
    <span> 
    <a href="http//google&id=111.com">123</a> 
    <a>hgi</a> 
    </span> 
    <span> 
    <a href="http//google&id=333.com">123</a> 
    <a>hgi</a> 
    </span> 

</td> 
</tr> 
</table> 

jQuery的

$(".zero span").each(function(){ 
$(this).find("a").attr("href").match(/id=/); 

}); 

但錯誤> _ < 爲什麼? 和 怎麼樣?

我想

id=222 
id= 333 
id= 111 
+0

,如果是動態生成的,爲什麼不直接使用真正的ID,即link,那麼目標是什麼? – 2014-08-31 15:29:33

+0

如果這些URL足夠多樣和複雜,您可能想嘗試使用deparam函數[在此處引用](http://stackoverflow.com/questions/1131630/the-param-inverse-function-in-javascript-jquery)而不是寫自己的 – iabw 2014-08-31 15:54:26

回答

1

您的某些<a />元素沒有href屬性。在這種情況下,attr()將返回undefined。當試圖在undefined上調用match()時,JavaScript會引發錯誤。

與修復:

$(".zero span").each(function(){ 
    href = $(this).find("a").attr("href"); 
    if (href !== undefined) { 
     href.match(/id=/); 
    } 
}); 

或改變選擇,包括a[href]

外:

$(".zero span a[href]").each(function(){ 
    $(this).attr("href").match(/id=/);   
}); 

內幕:

$(".zero span").each(function(){ 
    $(this).find("a[href]").attr("href").match(/id=/); 
}); 
0

你需要這樣的:

$(".zero span").each(function(){ 
    alert($(this).find("a").attr("href").match(/id=\d+/)[0]); 
}); 
0

你試過

$(this).find("a").attr("href").match(/id=.*/); 

,將匹配ID和之後的所有字符。