2014-10-20 155 views
0

最接近的div我有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(); 
}); 

有没有更好的方法来做到这一点?

回答

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

这样,你可以将其更改为使用类

+0

'#wrapper'没有兄弟姐妹 – Musa 2014-10-20 17:16:12

+1

应该是'$(this).closest(“#content”)'来获取正确的父亲。 – scrappedcola 2014-10-20 17:21:19

+0

@scrappedcola我认为内容是整个页面和子内容可以模块化 – qwertymk 2014-10-20 17:34:40

0

我想这可以帮助你

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

Hiding the closest div with the specified class

+0

你意识到他正在寻找最亲密的兄弟姐妹,而不是最亲密的父权?你的回答并不能解决手头的问题。 – scrappedcola 2014-10-20 17:17:52

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> 
相关问题