Jquery条件语句

时间:2011-10-17 21:21:33

标签: javascript jquery

我真的很抱歉,如果这是愚蠢的,但我到处搜索,但我没有找到任何关于如何去做的提示。 我有这个变量

 var id = $('#sometextfield').val(); 

此文本字段值是动态生成的,例如

 <input type="text" name="id" id="id" value="<?php echo $_get[something];?>" />)

这里的问题是我有一个if条件说

if(id == 100 || id ==120) {
   // i have these variables
   var mulitiplier = 0.005
   var price = (some alog) * mulitiplier;

   // do some very long piece of code
}
else if (id == 200 || id == 220) {
   // Then i have these variables
   var mulitiplier = 0.090;
   var price = (some alog) * mulitiplier;
   // Do the same very long piece of code(its practically the same thing as 
   // the first if statement and the only change is the ariable multiplier)        
}

这是有效的,但除此之外没有任何方法可以不重复同样的事情。我不喜欢它的外观。 非常感谢提前..

4 个答案:

答案 0 :(得分:3)

function long_piece(multiplier){
    ... long piece of code....
}
var MultMap = {100:0.005, 120:0.005, 200:0.009, 220:0.009}

long_piece(MultMap[id])

答案 1 :(得分:3)

只需将很长一段代码抽象出一个以multiplierprice值为参数的函数。例如

var theCode = function (multiplier, price) {
  do some very long piece of code
};

if(id == 100 || id == 120) {
  var mulitiplier = 0.005
  var price = (some alog) * mulitiplier;
  theCode(multiplier, price);
} else if (id == 200 || id == 220) {
  var mulitiplier = 0.090;
  var price = (some alog) * mulitiplier;
  theCode(multpilier, price);
}

注意:您应该考虑在parseIntid的初始化中使用===来比较此类代码的值而不是==

答案 2 :(得分:1)

简单,只需将“非常长的代码”放入自定义函数中,接受1个参数,即乘数。

答案 3 :(得分:0)

在函数中包装长代码并重写代码会更有效(也更可读),我想:

var id100120 = id === 100 || id === 120,
    id200220 = id === 200 || id === 220,
    multiplier = id100120 ? 0.005 : id200220 ? 0.090 : null,
    price = (/*some alog*/) * mulitiplier,
    longPieceOfCode = function(){ /* your code here ... */ };

if (id100120 || id200220) {
  longPieceOfCode();
}

如果id是字符串值,您还可以使用以下内容:

var id100120 = '[100][120]'.indexOf('['+id+']')>-1,
    id200220 = '[200][220]'.indexOf('['+id+']')>-1

或(除了ie&lt; 9我认为)

id = Number(id);
var id100120 = [100,120].indexOf(id) > -1,
    id200220 = [200,220].indexOf(id) > -1
相关问题