2013-02-28 72 views
0

我有一个非常简单的字符串比较,但检查总是失败。我试图加载在<img>加载基础上,window宽度不同的图像。两个网址的字符串比较失败

$(document).ready(function() { 
    var width = $(window).width(); 
    console.log(width); 
    $('.slider-image').each(function() { 
     resize_image($(this), width); 
    }); 
}); 

$(window).resize(function() { 
    var width = $(window).width(); 
    $('.slider-image').each(function() { 
     resize_image($(this), width); 
    }); 
}); 

function resize_image(image, width) { 
    console.log(width); 
    if(width >= 480 && width < 768) { 
     if(image.attr('src') != image.data('phone-src')); { 
      console.log('resize phone'); 
      image.attr('src', image.data('phone-src')); 
     } 
    } else if (width >= 768 && width < 960) { 
     if(image.attr('src') != image.data('tablet-src')); { 
      console.log('resize tablet'); 
      image.attr('src', image.data('tablet-src')); 
     } 
    } else if (width >= 960) { 
     if(image.attr('src') != image.data('desktop-src')); { 
      console.log('resize desktop'); 
      image.attr('src', image.data('desktop-src')); 
     } 
    } 
}; 

现在,我想要发生的是,don't replace the src, if the width remains within the borders。我试图通过检查src属性是否已具有data属性来执行此操作,但字符串检查失败,因为它始终不相等,尽管这两个属性在Chrome Inspector中都是相同的。为什么会发生?

顺便说一句,这两个字符串是图像的URL。

+1

什么'的console.log(image.attr( 'SRC'),image.data( '电话-SRC'))'打印? – 2013-02-28 16:15:10

+0

在每次比较之前添加一些带标签的调试语句,例如 的console.log( 'DEBUG1',image.attr( 'SRC'),image.data( '电话-SRC')); 通过这种方式,您可以检查执行哪个'if'分支以及您正在比较哪些值。 – nick 2013-02-28 16:16:32

+0

@ÁlvaroG.Vicario的“SRC”打印可点击的链接,以及'data'打印非可点击的链接。除此之外,它是相同的URL。 – tolgap 2013-02-28 16:38:30

回答

0

的问题是,我不得不每隔背后偷偷摸摸分号if语句...删除那些和它的工作。

0

你可能会检查SRC是一个字符串原始或字符串()。

new String("hi") == new String("hi"); // false 
+1

我为什么要这么做?我需要调用该对象... – tolgap 2013-02-28 16:13:47

+0

对不起,更新了我的答案jQuery的方法,因为我最初误解了这个问题。 – 2013-02-28 16:20:45

1

为什么在控制台登录后出现额外的圆括号?

console.log('resize phone')); 

我检查比较srcdata ATTRS,和他们相匹配。除非你的图像没有标记为data-phone-src=""等,我认为该行阻止设置src。