jquery fail to retrieve accurate data from sibling field
wonder what's wrong
<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);
},
});
});
IDs of elements have to be unique throughout the document. That means, elements cannot share the same ID (same as every person (should ;)) have a unique ID card).
If you have multiple IDs it will only select the first one occurring in the DOM tree, that is why it does not work for the second row.
You have to use classes instead:
<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));
},
});
};
精彩评论