在IF语句中执行jquery函数?

时间:2015-07-17 10:34:17

标签: javascript jquery

我正在尝试在IF语句中执行jquery函数。

基本上,我得到一个select选项的值,如果所选选项的值是我想要的(htl in this example),那么我想执行该函数!

但是当我在IF语句中包装代码时,我得到语法错误,我不知道是什么导致了这个问题。

这是我的全部代码:

var ascending = false;
$('.page_navigation .sortBy').change(function () {    
    var vals = $(this).val();
    if (vals == "htl") {    
        ///// I need to put the code bellow here    
    }
    var sorted = $('.mypro').sort(function (a, b) {
        return (ascending == (convertToNumber($(a).find('.prod-price').html()) < 
                  convertToNumber($(b).find('.prod-price').html()))) ? 1 : -1;
    });
    ascending = ascending ? false : true;

    $('#myCont').html(sorted);
});
var convertToNumber = function (value) {
    return parseFloat(value.replace('£', ''));
}

有人可以就此问题提出建议吗?

我试过这个,我得到语法错误:

var ascending = false;

$('.page_navigation .sortBy').change(function(){

    var vals = $(this).val();
    if(vals == "htl") {


    var sorted = $('.mypro').sort(function(a,b){
        return (ascending ==
               (convertToNumber($(a).find('.prod-price').html()) < 
                convertToNumber($(b).find('.prod-price').html()))) ? 1 : -1;
    });
    ascending = ascending ? false : true;

    $('#myCont').html(sorted);
});
var convertToNumber = function(value){
     return parseFloat(value.replace('£',''));
}
}

3 个答案:

答案 0 :(得分:5)

你关闭了如果错了。你需要在函数调用中放置右括号(if语句),所以:

var ascending = false;

$('.page_navigation .sortBy').change(function(){

    var vals = $(this).val();
    //closing brace matches this opening one
    if(vals == "htl") {    
          var sorted = $('.mypro').sort(function(a,b){
          return (ascending ==
               (convertToNumber($(a).find('.prod-price').html()) < 
                convertToNumber($(b).find('.prod-price').html()))) ? 1 : -1;
       });
       ascending = ascending ? false : true;

       $('#myCont').html(sorted);
   //put the brace inside the function...i.e. close the if brace
   }
});
var convertToNumber = function(value){
     return parseFloat(value.replace('£',''));
}

错误的位是:

var convertToNumber = function(value){
     return parseFloat(value.replace('£',''));
//WHY's this brace here!
}
}

答案 1 :(得分:2)

将if块的范围限制为$('#myCont').html(sorted);

if(vals == "htl") {
    var sorted = $('.mypro').sort(function(a,b){
        return (ascending ==
               (convertToNumber($(a).find('.prod-price').html()) < 
                convertToNumber($(b).find('.prod-price').html()))) ? 1 : -1;
    });
    ascending = ascending ? false : true;
    $('#myCont').html(sorted);
}

答案 2 :(得分:0)

这正是您应该使用IDE进行编码而不是使用文本编辑器进行编码的原因

语法错误将立即突出显示,您将节省大量时间

看一下netbeans的截图:

enter image description here

相关问题