I'm trying to use a jquery data selector to add/remove a class to an element.
$("#side_categories .testbox").click(function () {
var category = $(this).data('category'); //get the category from the clicked button
if ($('#side_categories .testbox').hasClass('activated')) {
//otherInput is the hidden text input
$('#listings .deals:data("category"="+category+")').removeClass('activated');
} else {
$('#listings .deals:data("category"="+category+")').addClass('activated');
}
});
开发者_JS百科In my test box I have data-category set on each trigger to pass it over. The category going into data-category is filled in via php.
Can't seem to get this to work, have been seeing errors like:
regular expression too complex
[Break On This Error] while (m = matcher.exec(expr)) {
or when I'm using the older function written by james padolsey, i get the following:
uncaught exception: Syntax error, unrecognized expression: data
I just want to be able to add/remove classes from LI's based on checkbox selections.
Many thanks in advance!
Make it so you can filter by the data
value:
$('#listings .deals').filter(function(index) {
return $(this).data('category') == category;
}).removeClass('activated');
.filter()
in jQuery doc
WORKING CODE:
$("#side_categories .testbox").click(function () {
var category = $(this).data('category'); //get the category from the clicked button
var these_deals = $('#listings .deals').filter(function (index) {
return $(this).data('category') == category;
});
$('#listings .deals').removeClass('activated');
if (these_deals.hasClass('activated')) {
//otherInput is the hidden text input
these_deals.removeClass('activated');
} else {
these_deals.addClass('activated');
}
});
Fiddle: http://jsfiddle.net/maniator/CcfwX/
jQuery doesn't have a native :data()
selector. You will need to explicitly define it on $.expr[':'].data
, or use a plugin that adds it as a selector.
Would something like this work instead?
$("#side_categories .testbox").click(function () {
var category = $(this).data('category'); //get the category from the clicked button
$('#listings .deals[data-category*="' + category + '"]').toggleClass('activated');
});
Try using single instead of double quotes around category, like this:
...
$('#listings .deals:data("category"='+category+')').removeClass('activated');
} else {
$('#listings .deals:data("category"='+category+')').addClass('activated');
...
If that doesn't work, try various combinations of adding and removing double quotes, like this, for instance:
...
$('#listings .deals:data(category="'+category+'")').removeClass('activated');
} else {
$('#listings .deals:data(category="'+category+'")').addClass('activated');
...
I'm not an expert at jQuery selectors, but you seem to be trying to use the variable category, rather than the string "+category+", in your selector, which your current code isn't doing, since the selector is surrounded by single quotes rather than double quotes.
精彩评论