Reputation: 290
I want to create a generic/scalable class that is able to accept none or multiple variables and process it. I want to learn how to check which field is present, number of field passed and do something with it. The 'fruitstall' class can accept 0 or multiple number of fruits variable.
HTML:
<div class="fruitstall(apple,orange)"></div>
Script:
$('.fruitstall').click(function(event){
if (get first variable value and check if it is an apple) {
//Show apple image
} elseif (get the next variable value and check if it is an orange) {
//Show orange image
}
alert('Number of fruit chosen are ' + (count number of variable passed to class) + ' ; ' fruit(index0) + fruit(index1));
});
Pardon my fruit stall example, I thought it would be interesting to ask question in a more lively method. :)
Thank you very much.
Upvotes: 0
Views: 2044
Reputation: 10094
I don't know if that could work, but if you prepare you class String as a JSON one, you could use eval() to get an object from which you could enumerate arguments
function prepareAsJSON(className){
var JSON = "{list:function" + className + "{return arguments}}"
return JSON
}
var className = $("div").attr('class');
var st = prepareAsJSON(className);
var obj = eval(st)
obj.list() //should return arguments as an array
I would never do that in production code, but that's pretty funny
Cheers
Grooveek
Upvotes: 1
Reputation: 2789
Another way might be to use HTML5 data attributes:
<div class="fruitstall" data-fruits="apple,orange"></div>
Then your JS code could go:
var fruits = $(this).data('fruits').split(',');
which would get an array of all the fruits for the stall.
Upvotes: 3
Reputation: 70487
You can have multiple classes assigned:
<div class="apple orange" id="divId"></div>
And then do a split on them like so:
var classList =$('#divId').attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item=='someClass') {
//do something
}
});
Source: Get class list for element with jQuery
Upvotes: 3