jQuery if和else with filter

时间:2012-07-10 05:51:52

标签: javascript jquery if-statement

我有一个过滤器,并将此脚本用于过滤器。

filteredData = filteredData.filter(function() {
  var elm = $(this),
  price = parseInt('0' + elm.attr('data-price'), 10) || 0;
  if ($(price < 15)) {
    return !(250 <= price);
  } else {
    return !(sliderData <= price);
  }
});

但是出了点问题。价格值为15或更高。但代码永远不会进入else结构。

3 个答案:

答案 0 :(得分:2)

尝试从此行中删除$()函数调用:

if ($(price < 15)) {

应该是:

if (price < 15) {

$()函数返回一个对象,并且所有对象都是“真实的”,因此这段代码将始终进入if块而不是else块。

(顺便说一句,假设您修复了上述问题,在if分支内,您要返回的表达式!(250 <= price)始终为true,因为price将为< 15 {1}},所以你不妨在那时说return true;。)

答案 1 :(得分:1)

似乎你已经无意中放了'$'选择器:

尝试:     if(价格<15){ (...)

答案 2 :(得分:0)

我对您的if声明感到了一些问题。

filteredData = filteredData.filter(function() { 
            var elm = $(this), 
            price = parseInt('0' + elm.attr('data-price'), 10) || 0; 
            if (price < 15) { 
                return !(250 <= price); 
            } else { 
                return !(sliderData <= price); 
            } 
        });

这会有所帮助。

相关问题