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.

然而,我有一个局部视图,其中包含代码.这个局部视图(公共代码)被包装在一个表单标记周围.

我有:

<form id="Create">
// load common code in from partial view
</form>

<form id="Edit">
// load common code in from partial view
</form>

现在,在这段通用代码中,我需要将一个插件附加到多个字段,这样我就可以

$('#Create .myClass').plugin({ options here});

$('#Edit .myClass').plugin({options here});

所以代码基本相同.我想知道是否有一种方法可以让它寻找任何一个id?

Edit

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});

或者,如果你想要一堆表单元素,你可以在所有表单元素中添加一个类,然后在该类中搜索.这并不能让你节省限制搜索的速度,但如果我是你,我真的不会太担心.浏览器会在背后做很多新奇的事情来优化常见的操作——简单的类 Select 器可能会更快.

Jquery相关问答推荐

JQuery UI-AutoComplete未显示下拉菜单

逐个交换图像

从克隆的输入中读取数据属性,返回初始输入的值

禁用提交按钮,直到所有字段都有值

表单提交之前的jQuery函数

在范围内设置文本

标识符 (id) 是否有通配符 Select 器?

.slice(0) 在这里有什么意义?

调用 jquery ajax - .fail vs. :error

基于垂直滚动的jquery添加/删除类?

延迟后运行功能

如何使用 jQuery Select sibling 元素?

jQuery .live() 和 .on() 有什么区别

使用 jQuery 拖放防止单击事件

Isotope 和 Masonry jQuery 插件之间的区别

Url.Action 在我的 url 中放了一个 &,我该如何解决这个问题?

jquery可排序占位符高度问题

将多个 JavaScript 文件合并为一个 JS 文件

Bootstrap datepicker Select 后隐藏

小于 10 给数字加 0