如何在jquery上运行if-else语句?

时间:2012-04-27 11:48:34

标签: jquery jquery-selectors

我有以下代码。现在我想对它运行一个if-else语句,但它不起作用。对此有什么想法?

var num1 = $('#id1').val(); 
var num2 = $('#id2').val();

var newVal = (num1+2)*(num2/4);
var nextVal =(num1+4)*(num2/2);
var newArr = new Array();
newArr.push(newVal);
newArr.push(nextVal);

newArr.sort();

if(newArr.get(0)==newVal)
$("body").html("<p>works fine!</p>");
else $("body").html("<p>works awfully!</p>");

4 个答案:

答案 0 :(得分:3)

只需使用newArr[0]代替newArr.get(0)

答案 1 :(得分:1)

val将返回一个字符串,因此您可能需要转换为数字。您可以使用一元加运算符:

var num1 = +$('#id1').val(); // Now you get 5 instead of "5" 
var num2 = +$('#id2').val();

//The problem shows up here when you are doing string concatenation instead of addition in the first set of parenthesis
var newVal = (num1+2)*(num2/4);

if(newArr[0]==newVal) // .get is for jQuery collections, just use brackets on an array

答案 2 :(得分:0)

您在此行中使用大写字母V声明了“Var”:

Var newVal = (num1+2)*(num2/4);

此外,使用[index]而不是.get(index)

访问数组的元素

这是编辑过的代码:

  var num1 = 50;   
  var num2 = 100;

  var newVal = parseInt((num1+2)*(num2/4));
  var nextVal =parseInt((num1+4)*(num2/2));
  var newArr = new Array();
  newArr.push(newVal);
  newArr.push(nextVal);

  newArr = newArr.sort(function(a,b){return a - b});

  if(newArr[0]==newVal)
    $("body").html("<p>works fine!</p>");
  else
    $("body").html("<p>works awfully!</p>");​ 

答案 3 :(得分:0)

试试这个

var num1 = 50;   
  var num2 = 100;

  var newVal = (num1+2)*(num2/4);
  var nextVal =(num1+4)*(num2/2);
  var newArr = new Array();
  newArr.push(newVal);
  newArr.push(nextVal);

  newArr.sort();

  if(newArr[0]==newVal)
    $("body").html("<p>works fine!</p>");
  else
    $("body").html("<p>works awfully!</p>");