我希望能够从这种类型的代码中获取href:
<tbody>
<tr class="odd">
<td class=" sorting_1">
<a href="aURL">The Link Text</a>
</td>
</tr>
</tbody>
但我希望能够单击链接本身或 td。
这是我的 CoffeeScript :
$("#myID tr td").click (event)->
event.preventDefault()
link = $(event.target).find("a").attr("href")
$("#anAjaxPod").load(link)
如果单击 td,则此方法有效,但如果单击链接,则无效。
编辑:更新了问题,我首先使用了 find 。这只是我最后使用的代码
最佳答案
使用.find() ; .closest()就是爬上DOM树测试自身和祖先。这里 anchor 标记是 td 的子标记,因此您需要向下移动。因此,您需要查找或子选择器。
$(this).find("a").attr("href")
Closest get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
$("#myID tr td").click(function(event){
event.preventDefault()
link = $(this).find("a").attr("href");
$("#anAjaxPod").load(link);
});
Fiddle
关于javascript - Jquery 寻找最近的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16601317/