从表中的其他td获取其他值
getting the other values from other td in a table
好的,我有一个HTML表格,TR(tow(中有4个TD,如下代码所示:
<table>
<tr>
<td class="1">Lemon</td>
<td class="2">Orange</td>
<td class="3">Tea</td>
<td class="4"><a href=#" class="get">Get</a></td>
</tr>
<tr>
<td class="1">Apple</td>
<td class="2">Tomato</td>
<td class="3">Pineapple</td>
<td class="4"><a href="#" class="get">Get</a></td>
</tr>
</table>
我如何使用jQuery来制作,当点击#GET时,它将获得与它在同一表行中的类1、2、3的值。
例如,我点击第一行的#get,我会得到柠檬、橙子、茶作为结果。
我使用下面的jQuery代码,但它不起作用:
$(document).ready(function(){
$('a#get').click(function(e){
e.preventDefault();
var val1 = $(this).parent().find('td.1').html();
var val2 = $(this).parent().find('td.2').html();
var val3 = $(this).parent().find('td.3').html();
alert(val1 + val2 + val3);
});
});
关于我该怎么做或者我做错了什么,有什么想法吗?
谢谢!
请参阅工作演示
您应该使用唯一的id
,这里是修改后的代码:
$(document).ready(function(){
$('a.get').click(function(e){
e.preventDefault();
var val1 = $(this).closest('tr').find('td.1').html();
var val2 = $(this).closest('tr').find('td.2').html();
var val3 = $(this).closest('tr').find('td.3').html();
alert(val1 + val2 + val3);
});
});
使用parent
时,您将返回到td
,因为链接在其中,您需要返回到通过closest('tr')
完成的tr
。此外,html已被修改为链接元素具有唯一id。
<a href=#" class="get">Get</a>
您在td
元素内部调用.find()
,而实际上您需要在tr
中调用它,后者更高一级。
将$(this).parent().find(...)
替换为$(this).parent().parent().find(...)
。
(正如pimvdb所建议的,您应该使您的ID唯一。(
如果单元格只是数字的,那么在单元格中添加类是没有意义的——可以使用eq()
。
以下是我的做法:
$('#table-id tr').each(function() {
var tds = $(this).find('td');
$(this).find('a.get').click(function() {
alert(tds.eq(0).html() + tds.eq(1).html() + tds.eq(2).html());
return false;
});
});
相关文章:
- 如何添加浮动和非浮动,其他
- 与其他库的jQuery.noConflict()
- 播放当前视频时如何停止其他视频?JavaScript
- 剑道UI内联编辑:如何在点击其他按钮时隐藏按钮
- 制作一个不带HTML a标记但在动画播放完毕后指向其他页面的超链接
- 除修剪外的其他功能
- 正在获取生成的PHP td值
- 是什么让一个“;Uncaught RangeError:超过了最大调用堆栈大小“;错误(Chrome,在其他浏览器中显示
- Array.length似乎不起作用;console.log则显示其他情况
- 如何消除代码中的未定义和其他问题
- 如何覆盖锚点元素's href目标,并在我点击转到目标javascript时删除其他错误
- jquery代码在Mozilla中有效,但在其他浏览器上无效
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- 如何在td元素中添加监听器
- Jquery未定义函数正在停止其他操作
- 如何将我的javascript库公开给其他客户端使用
- Javascript阻止其他Javascript代码
- jQuery将td onclick值传递到其他表
- 从表中的其他td获取其他值
- 移动& lt; td>当其他
已被移除