Reputation: 1785
I've coded a function that works but that is ugly. I'm pretty sure there's a better way to do what I want and it probably turned out very ugly because I'm not really good in javascript :D
I have some html elements that may have a class called view-in-box
or view-in-box-640-480
. If the class is just view-in-box
, a dialog will appear with some defaults width and height, else it will show up with the width and height specified in the class name.
The html elements class can be something like: class='note comment ui-button view-in-box-300-200 footer star'
.
What I've done until now is select all the elements that have view-in-box
in it with:
$('body').delegate('[class*=view-in-box]','click', function(){
Then I take the whole class attribute and I loop on it to check whether I can find a view-in-box
or not.
Here is the (simplified) code:
$('body').delegate('[class*=view-in-box]','click', function(){
...
var class_array = $(this).attr('class').split(" ");
for (var i = 0; i < class_array.length; i++) {
if (class_array[i].search('view-in-box-') != -1) {
box_text = class_array[i];
break;
}
}
if (box_text !== null) {
box_array = box_text.split('-');
....
}
....
return false;
});
So I was wondering, is there a way to get back directly inside my function what matched the view-in-box
predicate? Like for example view-in-box
or view-in-box-233-455
. Or do I really have to get the full class attribute and split it.
Hope I'm clear, javascript confuses me! Thanks.
Upvotes: 3
Views: 322
Reputation: 272166
A regular expression can be used to simplify your code; you can replace the JavaScript string functions (split, indexOf, search etc) with a regular expression:
/(?:^|\s)view-in-box(-\S+)?(?:\s|$)/;
// (?:^|\s) -- non-capturing group that matches beginning of string or white-space
// (-\S+)? -- optional capturing group that match hyphen + one or more non-white-space characters
// (?:\s|$) -- non-capturing group that matches end of string or white-space
Example:
var rx = /(?:^|\s)view-in-box(-\S+)?(?:\s|$)/;
rx.exec("view-in-box"); // ["view-in-box", undefined]
rx.exec("view-in-box-foobar "); // ["view-in-box-foobar ", "-foobar"]
rx.exec("view-in-box-foo-bar"); // ["view-in-box-foo-bar", "-foo-bar"]
rx.exec("note comment ui-button view-in-box-300-200 footer star"); // [" view-in-box-300-200 ", "-300-200"]
rx.exec("view-in-boxXXXX"); // null
rx.exec("XXXXview-in-box"); // null
rx.exec("XXXX-view-in-box"); // null
Upvotes: 1
Reputation: 149594
You should use a custom data-*
attribute instead of classnames to store this data.
So instead of:
<div class="note comment ui-button view-in-box-300-200 footer star"></div>
Do yourself a favor and use:
<div class="note comment ui-button view-in-box footer star" data-size="300-200"></div>
Then you can just use $(el).data('size')
to get the value using jQuery.
Upvotes: 2