jquery
2010-10-04 88 views 0 likes 
0

我想用jQuery点击一个输入字段时,将一个名为'focused'的类添加到父li。如何给li添加一个类,它可能是jquery输入的第一,第二或第三个父项?

<form action="http://localhost/daikon2/index.php/projects/admin/newproject" method="post"><ul id="createproject"> 
<li id="proname" class=""> 
<label for='project_name'>Project Name</label> 
<div><input type="text" name="project_name" value="" id="project_name" size="20" /></div></li> 

<li id="tothou" class="" > 
<label for='total_hr'>Total hour</label> 
<div><input type="text" name="total_hr" value="" id="total_hr" size="10" /></div> 
</li> 
<li id="act" class=""><label for="active">Active</label><div><span>Yes<input type="radio" name="active" value="1" checked="checked" id="active" /></span><span>No<input type="radio" name="active" value="0" /></span> 

</div> 
</li> 
<li id="by" class""><label for='created_by'>By</label> 
<div><select name="created_by"> 
<option value="admin">admin</option> 
<option value="admin2">admin2</option> 
</select></div> 
</li><li id="noteli" class=""><label for='note'>Note</label> 
<div><textarea name="note" cols="90" rows="12" id="note" ></textarea></div> 
</li> 
<li> 
<input type="hidden" name="id" value="6" /> 

</li> 
<li id="submitbtn" class""><input type="submit" name="submit" value="Create New Project" /></li> 
</form> 
</ul> 

在此先感谢。

回答

2

您可以使用.closest()抓取到最接近的父母选择匹配,就像这样:

$(":input").focus(function() { 
    $(this).closest("li").addClass("focused"); 
}).blur(function() { 
    $(this).closest("li").removeClass("focused"); 
}); 

You an test it out here。一些附注:您的</form>应为</ul>#submitbtn元素需要=代替class""

+0

感谢笔记的详细信息。 – shin 2010-10-04 12:59:13

0

你问不知道是什么,但你可以尝试这样做:

$(this).closest('li').addClass('foobar'); 
相关问题