2010-04-07 19 views
1

獲取準確的數據不知道什麼是錯的元素的jQuery無法從同級場

<table id=tblDomainVersion> 

<tr> 
    <td>Version</td> 
    <td>No of sites</td> 
</tr> 

<tr> 
    <td class=clsversion>1.25</td> 
    <td><a id=expanddomain>3 sites</a><span id=spanshowall></span></td> 
</tr> 

<tr> 
    <td class=clsversion>1.37</td> 
    <td><a id=expanddomain>7 sites</a><span id=spanshowall></span></td> 
</tr> 

</table> 


$('#expanddomain').click(function() { 

    //the siblings result incorrect 
    //select first row will work 
    //select second row will no response 

    var versionforselected= $('#expanddomain').parent().siblings("td.clsversion").text(); 
    alert(versionforselected); 

    $.ajax({ 

     url: "ajaxquery.php", 
      type: "POST", 

     data: 'version='+versionforselected, 

     timeout: 900000,         

     success: function(output) {        

      output= jQuery.trim(output); 
      $('#spanshowall').html(output); 
     }, 

    }); 




}); 

回答

5

的ID必須是唯一整個文檔。這意味着,元素不能共享相同的ID(與每個人(應該;)相同)都有唯一的ID卡)。
如果您有多個ID,它將僅選擇DOM樹中出現的第一個ID,這就是爲什麼它不適用於第二行。

你必須使用代替:

<table id=tblDomainVersion> 
    <tr> 
     <td>Version</td> 
     <td>No of sites</td> 
    </tr> 
    <tr> 
     <td class=clsversion>1.25</td> 
     <td><a class=expanddomain>3 sites</a><span class=spanshowall></span></td> 
    </tr> 
    <tr> 
     <td class=clsversion>1.37</td> 
     <td><a class=expanddomain>7 sites</a><span class=spanshowall></span></td> 
    </tr> 
</table> 

$('.expanddomain').click(function() { 
    // 'this' refers to the clicked item 
    // store a reference to the 'this' to be used in the Ajax callback 
    var $this = $(this); 

    // if "td.clsversion" comes always before the other cell, you can also do this: 
    // var versionforselected = $(this).parent().prev().text(); 
    var versionforselected = $(this).parent().siblings("td.clsversion").text(); 


    alert(versionforselected); 

    $.ajax({ 
     url: "ajaxquery.php", 
     type: "POST", 
     data: 'version='+versionforselected, 
     timeout: 900000,         
     success: function(output) { 
      // assuming that "<span class=spanshowall></span>" comes always 
      // after the link, you can use `.next()`       
      $this.next().html(jQuery.trim(output)); 
     }, 
    }); 
};