jquery - 使用 jQuery 将类添加到焦点组特定 div

标签 jquery jquery-events onblur onfocus dom-traversal

在下面的代码中,我试图做到这一点,以便当选择(聚焦)输入时,关联字段集中的 formhead div 更改其背景颜色,并对其进行模糊处理变回来。我想通过在焦点相同的 div 中添加一个类,并在模糊时删除该类来实现此目的。 jQuery 最接近的概念在概念上与我想要做的最相似,但不合适,因为它只针对父 div。是否还有其他东西可以针对该类中最近的 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> 

最佳答案

您可以使用此行获取输入的.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 的类。

关于jquery - 使用 jQuery 将类添加到焦点组特定 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6176007/

相关文章:

javascript - 使用 jquery 切换表格行

html - 尝试使用 v-on :blur for making disappear a context menu. ..但它不起作用

jquery - onpopstate 事件不会在 Chrome/Safari 中触发

javascript - 调用事件后等待事件监听器完成

javascript - 如何等待 'end' 事件的 'resize' 然后才执行操作?

textarea - textarea onclick删除文本

javascript - ReactJS:在模糊而不是每次击键时保存输入值

jquery - 在 IE 中使用 jQuery 获取属性

javascript - 在转换(序列化)非表单数据以与 ajax 一起使用的 javascript 中是否有更标准化的方法?

jquery - 添加显示的叠加 DIV 的延迟和过渡的最佳方法是什么?