2011-12-25 81 views
0

我很难在jQuery中选择输入元素的直接父div,这里是我迄今为止尝试的,我还包括输出I从每一个得到当我试图加紧进行bunso的占位符的文本框中输入:如何选择jquery中元素的直接父母

<script src="jq.js"></script> 
<script> 
$(function(){ 
    $('#grand_lolo').keypress(function(e){ 
     var box = $(this).parents('div').attr('id'); //undefined 
     var box2 = $(this).parent().closest('div').attr('id'); //undefined 
     var box3 = $(this).parent().attr('id'); //(an empty string) 
     var box4 = $(this).find("div:first").attr("id"); //lolo 
     var box5 = $(this).find("div").attr("id"); //lolo 
     var box6 = $(this).find("div:last").attr("id"); //apo 
     var box7 = $(this).closest('div').attr('id'); //grand_lolo 
     console.log(box); 
     console.log(box2); 
     console.log(box3); 
     console.log(box4); 
     console.log(box5); 
     console.log(box6); 

     console.log(box7); 
    }); 


}); 
</script> 
<div id="grand_lolo"> 
    <input type="text" placeholder="grand_lolo"/> 
    <div id="lolo"> 
     <input type="text" placeholder="lolo"/> 
     <div id="mama"> 
      <input type="text" placeholder="mama"/> 
      <div id="ate"> 
       <input type="text" placeholder="ate"/> 
      </div><!--end of ate--> 

      <div id="bunso"> 
       <input type="text" placeholder="bunso"/> 
      </div><!--end of bunso--> 
     </div><!--end of mama--> 

     <div id="papa"> 
      <input type="text" placeholder="papa"/> 
      <div id="kuya"> 
       <input type="text" placeholder="kuya"/> 

       <div id="apo"> 
        <input type="text" placeholder="apo"/> 
       </div><!--end of apo--> 
      </div><!--end of kuya--> 
     </div><!--end of papa--> 
    </div><!--end of lolo--> 
</div><!--end of grand_lolo--> 

正如你可以看到正确的输出应该直接封闭输入元素的div ID。

+1

我将事件绑定到INPUT字段而不是父容器会更正确。 – Nazariy 2011-12-25 04:08:42

+0

您将绑定到顶级div'grand_lolo'的按键,所以您的处理函数中的'this'不会是一个输入框。如果您想要生成按键的文本框,请尝试使用'e.target' – spb 2011-12-25 04:12:30

+0

要构建前面的注释,您要将该处理程序添加到'#grand_lolo'的'input'后代,可以使用'$('#grand_lolo input ').keypress(...'或$('#grand_lolo')。delegate('input','keypress',...'。如果您使用最新的jQuery,则使用'.on()'而不是'.delegate'(请参阅http://api.jquery.com/delegate/ http://api.jquery.com/on/)。如果输入元素将在后添加,则只需使用on/delegate处理程序已被绑定 – 2011-12-25 04:26:27

回答

2

只是附上keypressinput元素 - http://jsfiddle.net/hyEhh/

$('input').keypress(function() { 
    alert($(this).parent().attr('id')); 
}); 
+0

我的问题是,如果输入元素设置为只读,事件是否仍然执行? – 2011-12-25 04:31:58

+0

是的,它会 - http://jsfiddle.net/hyEhh/1/(前2个输入) – 2011-12-25 04:34:09

2

你在错误的方式在做。这样你就可以通过使用它的id来选择父div。 尝试类似

$('input[placeholder="grand_lolo"]')keypress(function(e){ 
    var box = $(this).parent().attr('id'); 
    console.log(box); 

}); 

如果你想为所有的输入做到这一点然后选择删除[placeholder="grand_lolo"]

2
$("input").each(function(){ 
    var id=$(this).parent().attr("id"); 
    $(this).attr("placeHolder",id); 
});