多个选择器不与上下文一起使用 [英] multiple selectors not working with context

查看:87
本文介绍了多个选择器不与上下文一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在focusin时选择一些表单元素,并为此:

$('textarea, input, select', '.highlightRow').live('focusin', function(e){ $(this).css("background-color","yellow"); });

但是多个选择器和上下文有问题

当我使用上下文和表单时没有.highlightRow,我的文本区域不会更改bgcolor(没关系),但是列表中的下一个元素(输入,选择)会更改bgcolor(这是错误的)

示例: http://jsfiddle.net/RgEAw/1/

现在只有不太优雅的解决方案可以了:

$('.highlightRow input, .highlightRow .highlightRow select, .highlightRow textarea')...

在这种情况下是否有可能使用此多重选择器和上下文?

解决方案

根据 jQuery文档 ,上下文必须是"DOM元素,文档或jQuery".它本身不能是字符串选择器.

因此,当您指定此选项时:

$('textarea, input, select', '.highlightRow')

您显然正在尝试指定'.highlightRow'的上下文,这不是已记录的指定上下文的方法之一.在这种情况下,您可以为'.highlightRow'获取单个DOM元素,将其转换为jQuery对象,或者将其放入实际的选择器中.

但是,仅当您要传递的对象确实存在时,上下文才会起作用.如果不存在,就好像您要传递一个NULL上下文,这意味着要搜索整个文档,这样它就不会做您想要的事情.因此,只有在选择器实际上存在上下文参数时,才可以使用它.

我建议使用:

$('.highlightRow textarea, .highlightRow input, .highlightRow select')

在此处工作的演示: http://jsfiddle.net/jfriend00/uzYuQ/.

i'm trying to select some form elements when focusin and with this:

$('textarea, input, select', '.highlightRow').live('focusin', function(e){ $(this).css("background-color","yellow"); });

but there is something wrong with multiple selectors and context

when i use context and form don't have .highlightRow my textarea not change bgcolor (it's ok) but next elements in list (input, select) change bgcolor (it's wrong)

example: http://jsfiddle.net/RgEAw/1/

now only less elegant solution work ok:

$('.highlightRow input, .highlightRow .highlightRow select, .highlightRow textarea')...

is there any posibilities to use this multiple selector and context in this situation?

解决方案

According to the jQuery doc, the context must be "a DOM Element, Document, or jQuery". It cannot itself be a string selector.

So, when you specify this:

$('textarea, input, select', '.highlightRow')

you are apparently trying to specify a context of '.highlightRow' which is not one of the documented methods of specifying a context. In this particular case, you can either get a single DOM element for '.highlightRow', turn it into a jQuery object or put it into the actual selector.

But, context will ONLY work if the object you are passing actually exists. If it doesn't exist, then it's like you're passing a NULL context which means to search the whole document so it doesn't do what you want. So, you can only use the context parameter in the selector when it actually exists.

I would suggest using this:

$('.highlightRow textarea, .highlightRow input, .highlightRow select')

Working demo here: http://jsfiddle.net/jfriend00/uzYuQ/.

这篇关于多个选择器不与上下文一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆