The Html:
<div id="div1" name="divname">Something</div>
<div id="div2" name="divname">Something else</div>
<div id="output"></div>
The Jquery:
$('[name="divname"]').click( function (){
var divnum = $(this).attr('id');
var divout = 'out' + divnum;
var outdiv1 = 'first div clicked';
var outdiv2 = 'second div clicked';
$('#output').html(divout);
});
Desired Result after div1 got clicked:
<div id="output">first div clicked</div>
Actual Result:
<div id="output">outdiv1</div>
Help Please.
You should do it this way:
That’s because if you say…
…
divoutis a string.But you want to access the variable whose name is the string which
divoutcontains.So the easiest way is creating an object, because you can access its properties like this:
So
If you know the name of the property:
obj.propertyorobj['property']If you don’t know its name but you have a variable
myvarwhich contains it:obj[myvar](myvar = 'property')EDIT:
Anyway, in that case I would use that:
It checks if
divnumis'div1'and, if yes, the result is'first div clicked'. If not,'second div clicked'.This way you don’t need any objects, only a conditional.