简体   繁体   中英

Jquery get closest a href attribute

I have the below markup and I am trying to get the href but always getting undefined. Any help is appreciated.

<div class="wrapper">
    <span class="mixSpanLeft" style="background-image: url(http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg)">
        <a href="http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg"></a>
    </span>
    <div class="mixDivRight">
        <p class="bottomP"><button>Select</button><p>
    </div>
</div>

$container = $('.wrapper');
$container.on('click', '.bottomP', function (event) {
    console.log($(this).closest('a').attr('href'));
});

Assuming that you fix the class/ID issue noted in the comments by Mohammad you could use:

$('.wrapper').on('click', '.bottomP', function (event) {
    console.log($(this).closest('.wrapper').find('a').attr('href'));
});

 $('.wrapper').on('click', '.bottomP', function (event) { console.log($(this).closest('.wrapper').find('a').attr('href')); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wrapper"> <span class="mixSpanLeft" style="background-image: url(http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg)"> <a href="http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg"></a> </span> <div class="mixDivRight"> <p class="bottomP"><button>Select</button><p> </div> </div>

Aside from what Mohammad mentioned about needing to use .wrapper instead of #wrapper. I recommend using .find() instead of .closest() . .closest() does not work in IE, but that might not be an issue for you. you can also do something like this:

$("div.wrapper").on('click', '.bottomP', function () {
    console.log($("div.wrapper a:first").attr('href'));
});

This will grab the first <a> tag inside the wrapper div.

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