具有多个类的 jQuery 元素:将一个类存储为 var
我正在尝试创建一个标准化的显示/隐藏元素系统,如下所示:
<div class="opener popup_1">Click Me</div>
<div class="popup popup_1">I'm usually hidden</div>
单击带有 opener 类的 div 应该显示()带有弹出类的 div。我不知道在任何给定页面上将有多少个开启器/弹出窗口组合,我不知道开启器和弹出窗口将在任何给定页面上的何处显示,而且我不知道如何给定的开启程序应该调用 show() 来处理许多弹出窗口。开启器和弹出窗口都必须能够拥有比 jQuery 使用的更多的类。
我想做的是这样的:
$(".opener").click(function() {
var openerTarget = $(this).attr("class").filter(function() {
return this.class.match(/^popup_([a-zA-Z0-9-_\+]*) ?$/);
});
$(".popup." + openerTarget).show();
这个想法是,当您单击 opener 时,它会从 opener 的类中过滤掉“popup_whatever”并将其存储为 openerTarget。然后将显示任何带有 class=popup 和 openerTarget 的内容。
I'm trying to create a standardized show/hide element system, like so:
<div class="opener popup_1">Click Me</div>
<div class="popup popup_1">I'm usually hidden</div>
Clicking on the div with the opener class should show() the div with the popup class. I don't know how many opener/popup combinations I'm going to have on any given page, I don't know where on any given page the opener and the popup are going to be displayed, and I don't know how many popups a given opener should call show() for. Both the opener and the popup have to be able to have more classes than just what's used by jQuery.
What I'd like to do is something like this:
$(".opener").click(function() {
var openerTarget = $(this).attr("class").filter(function() {
return this.class.match(/^popup_([a-zA-Z0-9-_\+]*) ?$/);
});
$(".popup." + openerTarget).show();
The idea is that when you click on an opener, it filters out "popup_whatever" from opener's classes and stores that as openerTarget. Then anything with class=popup and openerTarget will be shown.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://jsbin.com/ezizu3/edit
http://jsbin.com/ezizu3/edit
我倾向于认为这种事情使用 IDs:
with CSS:
和 JS:效果更好
I tend to think this kind of thing works better using IDs:
with CSS:
and JS:
这似乎是使用 HTML5 自定义数据属性的好例子。
HTML:
JS:
我认为这更干净,因为您不必使用 reg ex 解析元素的类。您可以向触发元素添加任意数量的任意其他类,并且触发器将导致弹出哪些元素仍然是显而易见的。
This seems like a good case to use the HTML5 custom data attributes.
HTML:
JS:
I think this is cleaner because you don't have to parse the element's classes with reg ex. You can add any number of arbitrary other classes to the triggering element and it will still be plainly obvious which elements the trigger will cause to pop up.