问题
I have 3 boxes and I want them to switch between them and also toggle off on a second click. Currently it switches between them fine (the IF part), but when I click on the same box to toggle it off if doesn't work (the "else if" part doesn't seem to work). I think I need to restructure the if-statement. Any help is greatly appreciated.
Here is the JS fiddle: http://jsfiddle.net/FFdjS/5/
Here is one of the element's click if-statement:
box1.click(function() {
if (box1.attr(strOff)) {
box1.attr(strOn);
box2.attr(strOff);
box3.attr(strOff);
} else if (box1.attr(strOn)) {
box1.attr(strOff);
} else {}
});
回答1:
Element.attr(...)
sets the attribute when object is passed as argument. Returns Element. If you want to toogle it - use something like this:
box1.click(function() {
if (box1.attr('stroke-width') == 1) {
box1.attr(strOn);
box2.attr(strOff);
box3.attr(strOff);
} else if (box1.attr('stroke-width') == 5) {
box1.attr(strOff);
} else {}
});
Example on jsFiddle
回答2:
The if-else
statement you have created will always return true on the first if
...
The reason for this is, for the conditional, you are passing the result of a method that will always return true. As Raphaels attr Spec indicates, the method will return...
- The element (if attr name and value is passed)
- value (of the attribute if attr name is passed)
- array of values (if attr names are passed)
- the attr object (if nothing if passed)
So, you're essentially just setting
the box in that if statement, which will then return true. Instead, you should pass just the attr name you need to check and compare it to your value. Similar to,
if(box1.attr('stroke-width')=='5'){...}else{...}
来源:https://stackoverflow.com/questions/13653670/raphael-js-if-else-statement-not-toggling-on-click