Raphael.js - if / else statement not toggling on click

こ雲淡風輕ζ 提交于 2019-12-11 01:27:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!