Jquery得到最接近的href属性

时间:2016-10-17 16:46:44

标签: javascript jquery html

我有以下标记,我正在尝试获取href但总是未定义。任何帮助表示赞赏。

<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'));
});

2 个答案:

答案 0 :(得分:1)

假设你修复了Mohammad评论中提到的类/ ID问题,你可以使用:

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

答案 1 :(得分:0)

除了Mohammad提到需要使用.wrapper而不是#wrapper之外。我建议使用.find()代替.closest().closest()在IE中不起作用,但这对您来说可能不是问题。你也可以这样做:

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

这将获取包装器div中的第一个<a>标记。

相关问题