2015-07-28 104 views
0

的HtmljQuery的获得输入元素在不同的父元素

<div>         
    <div> 
     <input type="text" class="search_input form-control" placeholder="Search..."></div> 
     <span> 
     <img src="images/btn-reset-search.png" class="clear_text" alt=""> 
     </span> 
</div> 

我想要得到的输入字段,当我点击了具有类名形象:clear_text

我想:

$('.clear_text').parent().prev('input'); 
+0

您的代码看起来不错。在点击处理程序中,它变成'$(this).parent()。prev('input');' – lshettyl

回答

2

试试这个:

$('.clear_text').on("click", function() 
{ 
    $(this).closest("div").find("input"); 
}); 

它定位到第一父divclosest("div")),那么它里面搜索一个inputfind("input"))。如果您不确定div元素可能具有多少个输入,则可以使用input:first

0

尝试

$('.clear_text').parent().prev().find('input'); 
0

尝试使用以下溶液:

$(function(){ 
    $(".clear_text").click(function(){ 
    var inputField = $(this).parent().closest('input[type="text"]'); 
    }) 
}) 

OR

$(function(){ 
    $(".clear_text").click(function(){ 
    var inputField = $(this).parent().parent().find('input[type="text"]'); 
    }) 
}) 

inputField这里是所需的输入。

+0

我不认为这会起作用!您可能需要引用[.closest()](https://api.jquery.com/closest/) –

+0

我可以知道原因。 –

+0

Reson:在第一条评论中更新仔细查看链接 –

2

解决方案:

$(document).on('click', '.clear_text', function(){ 
    var $input = $(this).closest("div").find("input"); 
    //do whatever you want with $input, $input.val(), $input.addClass(), etc.. 
});