找到具有指定类的最近div

时间:2014-10-20 17:06:55

标签: javascript jquery html

我有DOM结构

<div id="content">
    <div id="wrapper">
        <input type="text" id="search" />
    </div>
</div>
<div class="subContent">
</div>
<div class="subContent">
</div>

我想在最接近输入框的输入框的输入事件上选择<div class="subContent">

$('#search').on('keypress', function(){
    $(this).parent().parent().next();
});

有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

$(this).closest('#wrapper').nextAll('.subContent').first()

这样你就可以改变它来使用类

答案 1 :(得分:1)

我想这可以帮到你

$("#search").click(function () {
    $(this).closest("div.module").hide();
});

可能重复

Hiding the closest div with the specified class

答案 2 :(得分:0)

使用此: -

 <html>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <div id="content">
        <div id="wrapper">
            <input type="text" id="search" />
            <div class="subContent" style = 'background-color:red;'>div1</div>
            <div class="subContent" style = 'background-color:red;'>div2</div>
            <div class="subContent" style = 'background-color:red;'>div3</div>
        </div>
    </div>
    </html>
    <script>
    $('#search').on('keypress', function(){
        $(this).next().css( "background-color", "blue" );
    });
    </script>
相关问题