Reputation: 993
I have a code like this
$(".class1 .class2").on('click', function(){
//Do something
});
I am trying to somehting like this using variables:
var1=".class1";
var2=".class2"
$(var1 var2).on('click', function(){
//Do something
});
I see var1
and var2
are set to right values, but everytime I try to use 2 variables as selector it fails. When I keep the click trigger unchanged and use var1
or var2
elsewhere in the code individually (just var1
or var2
but not in the same selector list) it works. Any tips?
I figure I use var3
concatenate var1
and var2
, but I am trying to reduce another variable.
Upvotes: 4
Views: 8344
Reputation: 318212
You're missing the space. Without it, it becomes .class1.class2
which means the element has to have both classes, not get the descendant of the first one, etc.
var1 = ".class1";
var2 = ".class2";
$(var1 + ' ' + var2).on('click', function(){
//Do something
});
Another option would be find()
$(var1).find(var2).on(...
Just doing $(var1 var2)
would be the same as var fail = var1 var2;
it's a syntax error.
Upvotes: 3
Reputation: 2869
Another option would be to use jQuery objects as your variables. This would avoid having to declare a third variable, which is pretty trivial to do, but if you really want to, there is a way.
This is assuming you are trying to apply the function to any element that has either class, which is not what your existing code example shows ($(".class1 .class2").on
) , but to me it seems like this is what you are actually asking for.
var var1 = $('.clickable');
var var2 = $('.anotherClass');
var1.add(var2).on('click', function() {
console.log('button clicked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="clickable">Click 1</button>
<button class="anotherClass">Click 2</button>
Upvotes: 4
Reputation: 5927
Your sample code has a JavaScript syntax error (there should be a plus sign between var1 and var2, if you intend to concatenate them). However, this would produce a selector ".class1.class2" which is not what you're looking for - this would find an element that has both classes, rather than elements that have either class1 or class2.
So, firstly, you need a plus sign to fix your syntax error. But then you'll need a comma between your class names to select the correct elements.
var1=".class1";
var2=".class2"
// Select ".class1,.class2" (either class1 or class2)
$(var1 + ',' + var2).on('click', function(){
//Do something
});
Upvotes: 2