jQuery中的多个选择器链接? [英] Multiple selector chaining in jQuery?
问题描述
通常,当我使用一个类作为选择器时,我会尝试使用"id"选择器,以便它不会搜索整个页面,而只会搜索该类所在的区域.
Normally when I use a class as a selector I try to use an "id" selector with it so it does not search through the entire page but only an area where the class would be.
但是我有一个包含代码的局部视图.此局部视图(通用代码)被包裹在一个表单标签周围.
However I have a partial view with code in it. This partial view (common code) gets wrapped around a form tag.
我有:
<form id="Create">
// load common code in from partial view
</form>
<form id="Edit">
// load common code in from partial view
</form>
现在,在此通用代码中,我需要将插件附加到多个字段,这样我就可以这样做
Now in this common code I need to attach a plugin to multiple fields so I would do
$('#Create .myClass').plugin({ options here});
$('#Edit .myClass').plugin({options here});
所以几乎是相同的代码.我想知道是否有一种方法可以让它查找任何一个ID?
So it's pretty much the same code. I am wondering if there is a way to make it look for either of the id's?
修改
当我的选择器有变量时,我遇到了问题
I am having problems with it when I have variables for my selectors
my.selectors =
{
A: '#Create',
B: '#Edit',
Plugin: ' .Plugin'
};
$(selector.A+ selectors.Plugin, selector.B+ selectors.Plugin)
似乎没有运行.
推荐答案
您可以将多个选择器与逗号组合:
You can combine multiple selectors with a comma:
$('#Create .myClass,#Edit .myClass').plugin({options here});
或者,如果要有一堆它们,可以将一个类添加到所有表单元素中,然后在该类中进行搜索.这样做并不能为您节省限制搜索的速度,但是老实说,如果您是我,我不会对此太担心.浏览器做了很多花哨的事情来优化后台的常见操作-简单的类选择器可能会更快.
Or if you're going to have a bunch of them, you could add a class to all your form elements and then search within that class. This doesn't get you the supposed speed savings of restricting the search, but I honestly wouldn't worry too much about that if I were you. Browsers do a lot of fancy things to optimize common operations behind your back -- the simple class selector might be faster.
这篇关于jQuery中的多个选择器链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!