read first column value from a rowspan
I have a table as shown below. Upon click on t开发者_如何学JAVAhe edit I want to have the value of the first TD, i.e date, how can I do that, even with the second row?
<table id="foo" border="1px">
<tr>
<td rowspan='3' id="date">
Monday5 </td>
<td id="Name">
Jim
<a href="#" class="edit">
edit
</a>
</td>
</tr>
<tr>
<td id="Name">
Remy
<a href="#" class="edit">
edit</a>
</td>
</tr>
</table>
first of all you should fix your html code, as the id
attribute is unique. I suggest you use the class attribute:
<table id="foo" border="1">
<tr>
<td rowspan="3" class="date">Monday</td>
<td>Cell A1 <a href="#" class="edit">edit</a></td>
</tr>
<tr>
<td>Cell A2 <a href="#" class="edit">edit</a></td>
</tr>
<tr>
<td>Cell A3 <a href="#" class="edit">edit</a></td>
</tr>
<tr>
<td rowspan="3" class="date">Tuesday</td>
<td>Cell B1 <a href="#" class="edit">edit</a></td>
</tr>
<tr>
<td>Cell B2 <a href="#" class="edit">edit</a></td>
</tr>
<tr>
<td>Cell B3 <a href="#" class="edit">edit</a></td>
</tr>
</table>
in the javascript code, I first check if there's a date in the current row, if not, get the first prev. row containing a date:
$("#foo a.edit").click(function(e){
var tr = $(this).closest("tr"),
date = tr.find("td.date");
if (date.length == 0) {
date = tr.prevAll(":has(td.date):first").find("td.date");
}
e.preventDefault();
alert(date.html());
});
see a working demo at: http://jsfiddle.net/roberkules/WwZPY/
sidenote: i noticed that you used uppercase and lowercase names for classes. I suggest to be more consistent and name them always upper or lowercase. and css classes are case sensitive, so in order to eliminate another error source, be consistent.
If I got you right, here how you can do it
$('a').click(function(e) {
e.preventDefault;
var tr = $(this).parents('tr').eq(0);
while (tr && !tr.find('td:first[rowspan]').length > 0) {
tr = tr.prev();
}
alert(tr.find('td:first').text());
})
And an example on jsfiddle: http://jsfiddle.net/yUpTV/1/
Thanks for the -1 :) This one works as it should.
$(".edit").click(function(e){
var parent_tr = $(this).parents("tr:first");
var child_rowspan = parent_tr.find("td[rowspan]");
if (child_rowspan.length == 0) {
name = parent_tr.prevAll("tr:has(td[rowspan]):first").find("td[rowspan]").text();
} else {
name = child_rowspan.text()
}
alert(name);
});
try this:
$(this).parents("tr").children("td:first").text()
Since the element is already identified, you can access it like so
$("#date").text();
精彩评论