最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery Finding the closest link? - Stack Overflow

programmeradmin0浏览0评论

I want to be able to get the href from this type of code:

<tbody>
  <tr class="odd">
    <td class=" sorting_1">
      <a href="aURL">The Link Text</a>
    </td>
  </tr>
</tbody>

but I want to be able to click on the link itself, or the td.

Here is my CoffeeScript:

$("#myID tr td").click (event)->
    event.preventDefault()
    link = $(event.target).find("a").attr("href")
    $("#anAjaxPod").load(link)

This works if one clicks on the td, but not if if one clicks on the link.

Edit: Updated question, I used find at first. This is just the last code I played with

I want to be able to get the href from this type of code:

<tbody>
  <tr class="odd">
    <td class=" sorting_1">
      <a href="aURL">The Link Text</a>
    </td>
  </tr>
</tbody>

but I want to be able to click on the link itself, or the td.

Here is my CoffeeScript:

$("#myID tr td").click (event)->
    event.preventDefault()
    link = $(event.target).find("a").attr("href")
    $("#anAjaxPod").load(link)

This works if one clicks on the td, but not if if one clicks on the link.

Edit: Updated question, I used find at first. This is just the last code I played with

Share Improve this question edited May 17, 2013 at 4:26 Derek asked May 17, 2013 at 4:18 DerekDerek 9,9537 gold badges31 silver badges34 bronze badges 1
  • From jquery doc : the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. – Quicksilver Commented May 17, 2013 at 4:23
Add a ment  | 

3 Answers 3

Reset to default 4

Use .find() ; .closest() is to climb up the DOM tree testing self and ancestors. Here anchor tag is the child of td so you need to descend down. So find or a children selector is what you need.

$(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

.closest() looks and self or ancestors where as you want to descendent, to find the descendent use find()

link = $(event.target).find("a").attr("href")

try this:

$(function(){
    $("#myID tr td").click(function(){
         Link = $(this).find("a").eq(0).attr("href");
         $("#anAjaxPod").load(Link);
         return false;
    })
})
发布评论

评论列表(0)

  1. 暂无评论