2011-05-30 83 views
3

在下面的代碼中,我試圖使其在選擇(聚焦)輸入時,關聯字段集中的「formhead」div更改其背景色,並在模糊時改回。我想通過在焦點上添加一個類到同一個div來完成此操作,並在模糊時刪除該類。最接近的jQuery在概念上與我正在嘗試做的最相似,但不合適,因爲它只會針對父級div。是否還有其他的東西會針對與該類最近的div,而不影響其他字段集中的其他類?或者我必須要更具體一些,並確定木頭等?使用jQuery將類添加到焦點上的組特定div

<fieldset> 
<div class="formhead">Heading Title 1</div> 
<div class="fieldleft"> 
    <label for="specificinput">Input Title</label> 
    <input type="text" class="forminput" id="specificinput"> 
</div> 
<div class="fieldleft"> 
    <label for="specificinput">Input Title</label> 
    <input type="text" class="forminput" id="specificinput"> 
</div> 
</div> 
</fieldset> 

<fieldset> 
<div class="formhead">Heading Title 2</div> 
<div class="fieldleft"> 
    <label for="specificinput">Input Title</label> 
    <input type="text" class="forminput" id="specificinput"> 
</div> 
<div class="fieldleft"> 
    <label for="specificinput">Input Title</label> 
    <input type="text" class="forminput" id="specificinput"> 
</div> 
</div> 
</fieldset> 

而jQuery的:

<script type="text/javascript"> 
$(document).ready(function() { 
    $('input').focus(function(){ 
    $(this).closest('.formhead').addClass('bluebg'); 
    }); 
    $('input').focus(function(){ 
    $(this).closest('.formhead').removeClass('bluebg'); 
    }); 
}); 
</script> 

回答

5

你可以輸入的.formhead這一行:

$(this).closest('fieldset').find('.formhead').addClass('bluebg'); 

你也可以寫爲(實際上是相同的,使用上下文):

$('.formhead', $(this).closest('fieldset')).addClass('bluebg'); 

我看到你的代碼最簡單的方法是這樣的:

$('input.forminput').bind('focus blur', function() { 
    $(this).closest('fieldset').find('.formhead').toggleClass('bluebg'); 
}); 

jsFiddle Demo

這將分配相同的處理程序onfocusonblur,這將只需撥動類的.formhead

+1

這工作就像一個魅力,美麗的解決方案 – hisnameisjimmy 2011-05-30 12:37:05

+1

謝謝,就是我在找什麼。 – bard 2015-11-17 10:03:28

-1

可以使用.next()

+0

'.next()'在這裏會有幫助嗎? – kapa 2011-05-30 12:43:26

1

您也可以在父<div>元素與fieldleft類使用closest()匹配,然後繼續使用prevAll()formhead兄弟姐妹:

$(document).ready(function() { 
    $("input:text").bind("focus blur", function() { 
     $(this).closest(".fieldleft").prevAll(".formhead").toggleClass("bluebg"); 
    }); 
}); 
+0

這似乎只適用於緊跟formhead div的輸入字段。下面的任何輸入都無法定位它,可能是由於prev – hisnameisjimmy 2011-05-30 12:33:57

+0

@hisnameisjimmy的限制,你說得對,必須在這裏使用'prevAll()'。回答相應更新,感謝您的領導:) – 2011-05-30 12:37:21