如何监听点击事件,点击后查找父div?

时间:2014-10-31 01:30:51

标签: javascript jquery html

如果我有像这样的HTML

<div class="col-xs-3">
    <h2>A</h2>
    <div class="abc">
        <div class="def"><a class="btn"></a></div>
        <h3>B</h3>
        <p><a class="btn">C</a></p>
    </div>
</div>

如何在<a class="btn">C</a>上收听点击事件,而不是找到<h2>A</h2>(A)的值?

这是我的尝试

$(document).on('click', '.btn', function (event) {
    var btn = event.target, container;
    container = $(btn).closest('h2');
    window.console.log(container);
    event.preventDefault();
});

1 个答案:

答案 0 :(得分:1)

$('.btn').on('click', function() {
  alert( $(this).closest('.abc').prev().text() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-3">
    <h2>A</h2>
    <div class="abc">
        <div class="close"><a class="btn"></a></div>
        <h3>B</h3>
        <p><a class="btn">C</a></p>
    </div>
</div>