【问题标题】:Javascript If statement in a For loop working in Chrome and Safari but not FirefoxFor 循环中的 Javascript If 语句在 Chrome 和 Safari 但不适用于 Firefox
【发布时间】:2014-01-30 15:13:43
【问题描述】:

作为 TeamTreehouse.com 竞赛学习过程的一部分,我正在学习编码和构建图片库。

这里是代码:http://jsfiddle.net/kylenoble/8Wf8r/,运行代码时的结果:http://jsfiddle.net/kylenoble/8Wf8r/embedded/result/。

我遇到的问题是单击嵌套在.item div 中的.i div。经过数小时的头撞墙后,我将其范围缩小到下面的 if 语句在 Chrome 和 Safari 中触发但在 Firefox 中不触发。

具体代码如下:

    //Loops through the infoUrl's and populates the info button with
    //infoUrl that matches the imageUrl

    for(i = 0, len = (picturesList.length - 1); i <= len; i ++) {
        var infoUrl = picturesList[i].infoUrl;
        var imageUrl = picturesList[i].imageUrl;
        var displayImage = 'url(' +imageUrl+ ')';
        var currentItemUrl = ($(this).css('background-image'));

        //Matches the imageUrl in the displayImage var with the  
        //corresponding infoUrl and opens the matched infoUrl when 
        //the 'info' button is clicked. 

        if (displayImage === currentItemUrl) {
            console.log('true');
            $('.i').click( function(event) {
                window.open(infoUrl);
                event.stopImmediatePropagation();
            });
        break;
        }
    }

我似乎无法弄清楚为什么 if 语句不会在 Firefox 中触发,但会在 Chrome 和 Safari 中触发。我非常感谢您可能提供的任何帮助,如果我在这个问题的任何一点上都不清楚,我深表歉意。

谢谢!

【问题讨论】:

  • 确保你声明你的变量:for(i = 0 应该是for(var i = 0
  • console.log(escape(displayImage)); console.log(escape(currentItemUrl)); 他们看起来一样吗?
  • 您是否记录了要比较的值?
  • 谢谢安迪。我更新了值。 epascarello 和 Jason P,感谢您的提示。 gpgekko 打败了我。这似乎是问题所在。值不一样。感谢您的帮助!

标签: javascript jquery firefox if-statement


【解决方案1】:

我在 Firefox 中检查了调试器,它显示了 displayImage 和 currentItemUrl 之间的差异。

currentItemUrl:"url("http://media.nara....ges/16/7/16-0651a.gif")"

显示图像:"url(http://media.nara.g...ges/14/14/14-1336a.gif)"

注意引号。我不知道为什么,但似乎 Firefox 以不同的方式返回 css 属性。

【讨论】:

  • 非常感谢!这非常有效。我添加了一个针对 Firefox 测试的 if 语句,如果 Firefox 测试为真,则将额外的引号添加到 displayImage 变量中。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-28
  • 2019-01-26
  • 2015-03-16
  • 1970-01-01
  • 2021-04-16
相关资源
最近更新 更多