问题描述
||
我有一个包含2个div的表单,每个div包含一组字段。
我想做这样的事情:
$(document).ready( function(){
$(\".sectionBox\").click( function(){
$(this).removeClass(\'dim\');
$(\".sectionBox\").not(this).addClass(\'dim\')
});
});
如果用户单击div本身或<input>
字段,则效果很好。但是,如果用户单击“ 2”字段,则该按钮不起作用-出现下拉菜单,并且我的div完全不响应。我如何确保他们做出回应:
选择框? (需要)
为了一切? (最好)
非常感谢!
澄清度
伙计们,非常感谢您到目前为止的回答。如果要单击div本身或该div中的任何内容,我只想在容器div
中添加.dim
。 @LiangliangZheng和@wdm-您的解决方案似乎将elements3ѭ添加到多个元素(我只想要容器div)。
这是我目前的位置:
$(\".sectionBox\").click( function(){
$(this).removeClass(\'dim\');
$(\".sectionBox\").not(this).addClass(\'dim\');
});
$(\"select\").focus( function(){
$(\".sectionBox\").addClass(\'dim\');
$(this).parent(\".sectionBox\").removeClass(\'dim\');
});
这似乎起作用。我应该做些什么使以上内容更可靠?
解决方法
我对您的问题做出一些假设,这是我建议的代码:
$(document).ready( function(){
$(\".sectionBox *\").focus( function(){
var $t = $(this).closest(\'.sectionBox\')
$t.removeClass(\'dim\');
$(\".sectionBox\").not($t).addClass(\'dim\');
})
.click(function(){$(this).trigger(\'focus\')});
});
您可以在这里看到小提琴http://jsfiddle.net/xy8VC/4/
更新:
$(document).ready( function(){
$(\".sectionBox\").addClass(\'dim\');
$(\".sectionBox\")
.click( function(){
$(this).removeClass(\'dim\');
$(\".sectionBox\").not(this).addClass(\'dim\')
})
$(\".sectionBox *\").focus( function(){
$(this).closest(\".sectionBox\").trigger(\'click\');
});
});
http://jsfiddle.net/xy8VC/6/
首先,我想指出的是,我的第一次尝试也会在您的容器中添加\'dim \'。如果您愿意采用发现的代码,那么我想分享三点:
$(document).ready(function(){
// Since your containers are not dynamic,wrap
// them into an array,so you don\'t need to call
// $() to select the containers every time.
var $box = $(\'.sectionBox\');
$box.addClass(\'dim\');
$box.click( function(){
$(this).removeClass(\'dim\');
$box.not(this).addClass(\'dim\');
});
// Also have input included.
$box.find(\"select,input\").focus( function(){
$box.addClass(\'dim\');
// Replace parent() with closest() for more
// flexibility,unless you are sure that all fields
// are direct-children to your container.
$(this).closest(\".sectionBox\").removeClass(\'dim\');
});
});
试试这个:http://jsfiddle.net/xy8VC/8/
, 您需要绑定到更改事件,而不是选择框的单击事件。
, 不知道这是否正是您要尝试执行的操作,但请查看此演示。
演示:http://jsfiddle.net/wdm954/xy8VC/3/
基本上,我正在做的就是将dim类应用于所有未重点关注的内容(此示例中的标签除外)。这仅使聚焦场处于完全不透明状态。
编辑:略微更改了我的代码以包含一个keyup
事件,该事件使它可以与制表符一起使用。
$(\'.sectionBox\').bind(\'click keyup\',function() {
$(this).removeClass(\'dim\')
.children().removeClass(\'dim\')
.not(\':focus,label\').addClass(\'dim\');
});