2012-01-11 174 views
0

我是jquery的noob。卡住,希望得到一些幫助。 目前正在構建一個工具來抓取特定頁面的數據。該網頁看起來是這樣的:基於id的jquery匹配元素

<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1"> 
<tbody> //This is data group 1  
    <tr id="parent0"> //Record 1 
    <td align="left"> <---------- text1 here -------> </td> 
    <td align="left"> <---------- text2 here -------> </td> 
    <td align="left"> <---------- text3 here -------> </td> 
    </tr>  
    <tr id="parent0"> //Record 2 
    <td align="left"> <---------- text1 here -------> </td> 
    <td align="left"> <---------- text2 here -------> </td> 
    <td align="left"> <---------- text3 here -------> </td> 
    </tr>  
</tbody> 
</table> 

<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1"> 
<tbody> //This is data group 2  
    <tr id="child0"> //Record 1 
    <td align="left"> <---------- text1 here -------> </td> 
    <td align="left"> <---------- text2 here -------> </td> 
    <td align="left"> <---------- text3 here -------> </td> 
    </tr>  
    <tr id="child0"> //Record 2 
    <td align="left"> <---------- text1 here -------> </td> 
    <td align="left"> <---------- text2 here -------> </td> 
    <td align="left"> <---------- text3 here -------> </td> 
    </tr>  
</tbody> 
</table> 

下面是jQuery的一個片段:

ancestor = $(this).closest("tr[id]"); 

    matchedElement = $(this).first(); 
    originalBgColor = $(matchedElement).css('background-color'); 
    $(matchedElement).css('background-color', 'green'); 
    $(matchedElement).bind('click.annotator', function(event) { 
    event.stopPropagation(); 
    event.preventDefault(); 
    self.port.emit('show', 
     [ 
     document.location.toString(), 
     $(ancestor).attr("child0"), 
     $(matchedElement).text() 
     ] 

我試圖從剛剛<tr>塊id爲parent0和child0捕獲所有數據。

在當前的工作狀態下,該工具將文本捕捉到兩個表格中的所有數據。理想情況下,我希望能夠分別捕獲所有<TR>塊,並將它們放入一個數組中,然後我可以迭代。

+3

的ID值必須是唯一的,而你目前分配同一個ID多個元素。 – Paul 2012-01-11 00:57:40

+2

請勿多次使用任何ID:http://www.w3.org/TR/html4/struct/global.html#h-7.5.2 – 2012-01-11 00:57:44

回答

0
$('tr[id="child0"]').each(function() { 
         //this will be fired for each matched element 
         $(this).doSomething(); 
         } 
        ); 

這種方式,您將得到所有TR id爲child0 檢查此鏈接瞭解更多參考http://api.jquery.com/category/selectors/

+0

謝謝!這有助於找出我的問題。 – spex2004 2012-01-19 01:06:53

2

它看起來像你使用ID元素,你應該使用一個類。

而不是

<tr id="child0"> 
<tr id="parent0"> 

做這個

<tr class="child0"> 
<tr class="parent0"> 

不像ID,您可以分配相同的值與類屬性的多個元素。

然後你可以選擇他們都喜歡這個

$("tr.child0,tr.parent0").each(
          function() { 
          //this will be fired for each matched element 
          $(this).doSomething(); 
          } 
         ) 
0

做這樣的..

$('cite.fn:contains(blabla)').css('color', 'red'); 

編輯:儘管那樣會匹配「blablablabla」湖

$('cite.fn').each(function() { 
    if ($(this).text() == 'blabla') { 
     $(this).css('color', 'red'); 
    } 
}); 

這應該更準確。

編輯:其實,我覺得這個方案是更優雅:

$('cite.fn').filter(function() { 
    return $(this).text() == 'blabla'; 
}).css('color', 'red');;