我有一张如下表:
<table>
<tr>
<td>james</td>
<td>sawyer</td>
<td><button id="getVal">Get</button></td>
<tr>
<tr>
<td>kate</td>
<td>deluna</td>
<td><button id="getVal">Get</button></td>
<tr>
<tr>
<td>tupac</td>
<td>shakur</td>
<td><button id="getVal">Get</button></td>
<tr>
</table>
我想点击“获取”#39;然后按钮获取tr中的所有td值。我试试这段代码,但它没有用。
<script type="text/javascript">
$(document).ready(function() {
$('#getVal').click(function () {
var name = $(this).find('td:first');
var surname = $(this).find('td:second');
});
});
</script>
我该怎么做?请帮帮我!
答案 0 :(得分:0)
您不能多次使用相同的id
。改为给他们class
。
它将改为:
<table>
<tr>
<td>james</td>
<td>sawyer</td>
<td><button class="getVal">Get</button></td>
<tr>
<tr>
<td>kate</td>
<td>deluna</td>
<td><button class="getVal">Get</button></td>
<tr>
<tr>
<td>tupac</td>
<td>shakur</td>
<td><button class="getVal">Get</button></td>
<tr>
</table>
只要您确定它始终是第一个和第二个<td>
,您就可以使用以下jQuery(仍然感觉很hacky)。
$('.getVal').click(function () {
var name = $(this).parent().parent().find('td:first').text();
var surname = $(this).parent().parent().find('td:nth-child(2)').text();
console.log(name);
console.log(surname);
});
一个有效的JSFiddle can be found here
答案 1 :(得分:0)
这样做,
<table>
<tr>
<td>james</td>
<td>sawyer</td>
<td><button class="get_button">Get</button></td>
<tr>
<tr>
<td>kate</td>
<td>deluna</td>
<td><button class="get_button">Get</button></td>
<tr>
<tr>
<td>tupac</td>
<td>shakur</td>
<td><button class="get_button">Get</button></td>
<tr>
</table>
然后根据课程选择你的td,如下所示。
<script type="text/javascript">
$(document).ready(function() {
$('.get_button').click(function () {
var name = $(this).find('td:first');
var surname = $(this).find('td:second');
});
});
</script>
答案 2 :(得分:0)
Please try this one
$(document).ready(function() {
$('.getVal').click(function () {
var name = $(this).parents('tr').find('td:nth-child(1)').text();
var surname = $(this).parents('tr').find('td:nth-child(2)').text();
alert(name);
alert(surname)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>james</td>
<td>sawyer</td>
<td><button class="getVal">Get</button></td>
<tr>
<tr>
<td>kate</td>
<td>deluna</td>
<td><button class="getVal">Get</button></td>
<tr>
<tr>
<td>tupac</td>
<td>shakur</td>
<td><button class="getVal">Get</button></td>
<tr>
</table>