开发者

jQuery element with multiple classes: storing one class as a var

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 a开发者_如何学JAVAnd stores that as openerTarget. Then anything with class=popup and openerTarget will be shown.


$('.opener').click(function() {
  var openerTarget = this.className.match(/\bpopup_\w+\b/);
  $('.popup.' + openerTarget).hide();
}​);​

http://jsbin.com/ezizu3/edit


I tend to think this kind of thing works better using IDs:

<div id="popup1" class="opener">Click Me</div>
<div class="popup popup1">I'm usually hidden</div>

with CSS:

div.popup { display: none; }

and JS:

$("div.opener").click(function() {
  $("div." + this.id).toggle();
});


This seems like a good case to use the HTML5 custom data attributes.

HTML:

<div data-popup-trigger="popup1">Click me!</div>
<div class="popup1">Secret information no one will ever see! Muahaha!</div>

JS:

$('[data-popup-trigger]').click(function() {
  var popupClass = $(this).attr('data-popup-trigger');
  $('.' + popupClass).show();
});

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜