[英]how to pull href attribute inside the table element
我有表格,表格的每个单元格都有特定的网址。 我正在尝试使用jquery获取特定单元格上的url。 这里的问题是没有为表,行和列定义类或ID。 只想仅使用标签来提取href属性。
<table>
<tr>
<td><a href='MytestSite11.com'>site21</a></td>
<td><a href='MytestSite12.com'>site22</a></td>
<td><a href='MytestSite13.com'>site23</a></td>
</tr>
<tr>
<td><a href='MytestSite21.com'>site21</a></td>
<td><a href='MytestSite22.com'>site22</a></td>
<td><a href='MytestSite23.com'>site23</a></td>
</tr>
<tr>
<td><a href='MytestSite31.com'>site21</a></td>
<td><a href='MytestSite32.com'>site22</a></td>
<td><a href='MytestSite33.com'>site23</a></td>
</tr>
</table>
我正在尝试获取第二行第二列的href元素,即MytestSite22。 我已经尝试过以下jquery代码,但是返回的是undefined。不确定在此遗漏了什么。
$(function () {
var $row = $('table tr').eq(1);
var $col=$row.eq(1)
alert($col.attr('href'));
});
您忘记在第二个变量中指定元素:
var $col=$row.find('td').eq(1)
然后,在其中指定锚点:
alert($col.find('a').attr('href'));
对于它的价值,通常使用美元字符作为变量前缀来表示数组或集合。 在这里,您正在单个项目上使用它。
这是第二行第二列的href元素
$("table tr:eq(1) td:eq(1) a").attr("href");
您可以一次完成所有操作: $('table tr:nth-child(2) td:nth-child(2) a').attr('href');
$(document).ready(function() { alert($('table tr:nth-child(2) td:nth-child(2) a').attr('href')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td><a href='MytestSite11.com'>site21</a></td> <td><a href='MytestSite12.com'>site22</a></td> <td><a href='MytestSite13.com'>site23</a></td> </tr> <tr> <td><a href='MytestSite21.com'>site21</a></td> <td><a href='MytestSite22.com'>site22</a></td> <td><a href='MytestSite23.com'>site23</a></td> </tr> <tr> <td><a href='MytestSite31.com'>site21</a></td> <td><a href='MytestSite32.com'>site22</a></td> <td><a href='MytestSite33.com'>site23</a></td> </tr> </table>
这是一种简单的方法:
var $row = $('table tr:nth-child(2)'), // row
$col = $row.children('td:nth-child(2)'), // column
$a = $col.children('a'); // anchor
alert($a.attr('href'));
:nth-child(n)
选择器将匹配共享父元素的子元素中处于特定索引的元素。 请注意,它是基于1的,而不是基于0的(例如,像JavaScript数组),因此第二个孩子是:nth-child(2)
,第三个孩子是:nth-child(3)
,依此:nth-child(2)
。
这是CodePen示例 。
尝试这个:
var a = $("tr").eq(1).find("td").eq(1).find("a").attr("href");
alert(a);
您还可以通过函数检索值的一种可能性:
getMe(RowNumber,ColumnNumber);
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(e) {
getMe(2,2);
});
function getMe(rowN, colN) {
var link = $("tr:eq("+(rowN-1)+") td:eq("+(colN-1)+") a").attr("href");
alert(link);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.