How to shift between variable names in jQuery and change them?
//predefined variables
var s1='';
var d2='';
//trying to change variables by .attr() parameter but no luck
$('body').on('click','span', function() {
var $(this).parent().attr('data-scan')=$(this).attr('id');
});
HTML
<div data-scan="s1"><span id="banana">Banana</span><span id="apple">Apple</span></div>
<div data-scan="d2"><span id="orange">Orange</span><span id="apple">Apple</span></div>
How can I change specific variables? I do’t care about changing attr papameter, all I need is changing predefined global var parameters!
Firstly, your html for the
data-scanattributes is wrong, you have no closing quotes.Secondly, you can the
data()jquery function to accessdataattributes.Thirdly, you cannot set values by using the
=operator.You want something like this:
or, without the
data()function:Here is a working example
To get the value you can do one of the following:
or
Your exact requirements for setting a variable based on the data-scan value
Based on your comments and code, I think it has not been clear what you were trying to do. I think I have worked it out though and you want to use the
data-scanvalue to determine which global variable should be set…Here is an example of what I think you are trying to do.
However, if you have lots of variables then it is not ideal to use so many if/else statements. So you could use the javascript
eval()function.See here for an example
But be careful the your eval code is subjected to user injected values (not that javascript is safe from users anyway)