javascript - Jquery 寻找最近的链接?

标签 javascript jquery coffeescript

我希望能够从这种类型的代码中获取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/

相关文章:

javascript - Firefox 开发人员控制台中的 XML 解析错误

jquery - 使用 jQuery 检查元素是否为 'display:none' 或阻止单击

javascript - 使用 .map 或 underscore.js 在 javascript 中重构 while 循环

javascript - CoffeeScript 被转换为错误的 javascript

javascript - 在 javascript 中用 php 代码编写

javascript - 如何在更改时更改按钮的类别?

javascript - 如何使过渡效果增加变化的输入

javascript - 从 javascript 数组中删除元素的简洁方法(使用 jQuery、coffeescript)

javascript - bxslider javascript slider 不工作

javascript - URLSearchParams 无法追加数组