我很難在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。
我將事件綁定到INPUT字段而不是父容器會更正確。 – Nazariy 2011-12-25 04:08:42
您將綁定到頂級div'grand_lolo'的按鍵,所以您的處理函數中的'this'不會是一個輸入框。如果您想要生成按鍵的文本框,請嘗試使用'e.target' – spb 2011-12-25 04:12:30
要構建前面的註釋,您要將該處理程序添加到'#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