Jquery-获取表中第一个td的值
当用户点击“点击”时,我试图获得每个tr中第一个td的值。
以下结果将输出aa,ee或ii。 我正在考虑使用最近的(’tr’)..但它总是输出“对象对象”。 不知道该怎么做。
我的HTML是
aa bb cc dd click ee ff gg hh click ii jj kk ll click
jQuery的
$(".hit").click(function(){ var value=$(this).// not sure what to do here alert(value) ; });
$(this).parent().siblings(":first").text()
parent
给你链接周围的
,
siblings
给出了
所有
标签,
:first
给出集合中第一个匹配的元素。
text()
给出了标签的内容。
这应该工作:
$(".hit").click(function(){ var value=$(this).closest('tr').children('td:first').text(); alert(value); });
说明:
-
.closest('tr')
获取最近的祖先,它是一个
元素(所以在这种情况下是
元素所在的行)。
-
.children('td:first')
获取此元素的所有子元素,但使用:first
选择器将它缩减为第一个 -
.text()
获取元素内的文本
从其他答案中可以看出,实现这一目标的方法不止一种。
在上面的具体情况中,你可以做父母/孩子的杂耍。
$(this).parents("tr").children("td:first").text()
$(".hit").click(function(){ var values = []; var table = $(this).closest("table"); table.find("tr").each(function() { values.push($(this).find("td:first").html()); }); alert(values); });
你应该避免使用$(".hit")
这是非常低效的。 请尝试使用事件委派。
安装firebug并使用console.log
而不是alert
。 然后,您将看到您访问的确切元素。
如果你需要在没有为它们定义id的情况下获取tr里面的所有td,你可以使用下面的代码:
var items = new Array(); $('#TABLE_ID td:nth-child(1)').each(function () { items.push($(this).html()); });
上面的代码将表中的所有第一个单元格添加到Array变量中。
你可以改变nth-child(1) ,这意味着第一个细胞到你需要的任何细胞数。
希望这段代码可以帮到你。