我正在尝试在 IF 语句中执行 jquery 函数。
基本上,我正在获取选择选项的值,如果所选选项的值是我想要的(本例中为htl)
,那么我想执行该函数!
但是当我将代码包装在 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('£',''));
}
}
最佳答案
您关闭了 if 错误。您需要将(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!
}
}
关于javascript - 在 IF 语句中执行 jquery 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31473855/