简体   繁体   中英

.attr("href") returning undefined

Here is a simplified version of my HTML

<div class="post-title-div">
    <a href="link" class="post-title">Link</a>
</div>
<div></div>
<div>
    <img class="eye-icon" src="link.jpg"/>
</div>

JavaScript:

  $(".eye-icon").click(function(){
    var link = $(this).parent('.post-title-div').find(".post-title").attr("href");
  })

alert(link) returns undefined, why?

$(this).parent('.post-title-div').find(".post-title") by itself returns [object Object]

Parent / Parents / Closest is not what you're after :

 $(".eye-icon").click(function(){

    var link = $(this).parent().prev().prev().find(".post-title").attr("href");
   alert(link)
  })

You don't have a common parent there.

http://jsbin.com/tupeta/edit?html,js,output

However , I suggest that you add a new container which will contain them all . something like :

<div class='wrapper'> 
 <div class="post-title-div">
    <a href="link" class="post-title">Link</a>
</div>
<div></div>
<div>
    <img class="eye-icon" src="link.jpg"/>
</div>
</div> 

So now you can do :

 $(".eye-icon").click(function(){

    var link = $(this).closest('.wrapper').find(".post-title").attr("href");
   alert(link)
  })

The parent of the <img> is the nondescript <div> which surrounds it. jQuery then looks in that div for '.post-title-div' , doesn't find anything and returns an empty selector object. In that empty selector it then looks for .post-title and - naturally - doesn't find anything either. It then tries to read an attribute on the new, also empty, selector, which of course can't return anything useful.

The reason why $(this).parent('.post-title-div').find(".post-title") returns an [object Object] is because jQuery selectors never return undefined, they always return another selector, which can be an empty selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM