2012-07-12 128 views
1

我的IDE,RubyMine的,说这是“可能不正确的”。这个javascript为什么不正确?

function update_top_up_prices_via_localStorage(){ 
    var index = localStorage.getItem("volxs"); 
    $('.product-inner').each(function(){ 

     var product = this.getAttribute('data-product-miles'); 
     var cpm = ((localStorage.getItem("cpm_by_volxs_"+product)).split(","))[index]; 

     $(this).find('table tbody tr td').each(function(){ 
      var top_up_miles = Number(this.getAttribute('data-topup-miles')); 
      var price = Number(top_up_miles * cpm * 1.06); 
      price = price.toFixed(2); 
      $(this).text('\u00A3'+price); 
     }) 
    }); 
} 

我的IDE上var top_up_miles线,“潜在的无效使用this这种检查的JavaScript this说是相同的封闭物,在外部环境。

JS的工作在Chrome和IE9的罚款。它不会在IE8工作。

这是错的?有没有更好的方式来写这个?

+0

我不知道RubyMine(实际上不知道这是什么),但你的代码看起来或多或少。奇怪的纯JavaScript和jQuery混合。尝试使用'$(this).attr('data-topup-miles')'。 “你不能在IE8中工作”是什么意思?任何错误?不正确的值(IE8似乎以不同于其他浏览器的方式处理'toFixed')?另外IE8有控制台('F12'我相信) - 检查那里的错误(你真的需要在加载页面之前触发控制台,我认为)。 – freakish 2012-07-12 11:50:26

回答

3

RubyMine不知道$().each使用指定的this上下文执行传递的函数。如果你想避免这种警告,使用

$(/* ... */).each(function (i, elem) { 
    elem.getAttribute(/* ... */); 
}); 

您的代码不与IE8工作的原因可能有无关这一点。对于更大的兼容性然而,使用jQuery包裹的功能,而不是原生API功能:$(this).attr代替this.getAttribute(感谢@freakish)

1

它提请你注意提醒你,你应该小心使用JavaScript中的this关键字,如this总是指功能拥有者。请参阅this article on quirksmode on the JavaScript this keyword

+0

你用'Function.call'或'Function.apply'设置'this'。这是jQuery在这里所做的。 – 2012-07-12 11:56:42

+0

@OttoAllmendinger - 这可能是事实,但无关紧要。我只是在谈论OP关于IDE警告的问题。感谢您的反馈,很好的回答顺便说一句 – 2012-07-12 12:05:13

相关问题