不能在函数外移动变量使用

时间:2018-02-01 08:23:25

标签: javascript

我真的很挣扎。我创建了一个表单,根据帐篷中的人数以及是否使用信用卡付款来计算该人的欠款。金额根据选择更新。当用户提交时,他们应该被重定向到PayPal,其总金额在网址的末尾,即:

PayPal.me/240英镑240英镑或PayPal.me/600英镑600英镑

问题是我的价格变量超出了我设定重定向的其他功能,价格金额从未进入重定向。

这就是我的尝试:

HTML:

    <select name='field_0' id='field_0' class='text_select' onchange="pricecalc()"   >  
<option value="2 people" >2 people</option> 
<option value="3 people" >3 people</option> 
<option value="4 people" >4 people</option> 
<option value="5 people" >5 people</option> 
<option value="6 people" >6 people</option> 
</select>

    <select name='field_1' id='field_1' class='text_select' onchange="pricecalc()"   >  
<option value="Bank transfer" >Bank transfer</option>   
<option value="Debit card" >Debit card</option> 
<option value="Credit card + 3.4%" >Credit card + 3.4%</option> 
</select>         
<b>Total Price</b>
<span id="cost">Hello World!</span>
<b>Price Each</b>
<span id="costeach">Hello World!</span>

相关JS:

var myprice;
function pricecalc() {
  var a = document.getElementById("field_0");
  var quantity = a.value.substring(0, 1);
  var b = document.getElementById("field_1");
  var type = b.value;

  if (quantity == '2') {
    var rate = '120';
  } else if (quantity == '3') {
    var rate = '110';
  } else {
    var rate = '100';
  }

  myprice = rate * quantity;
  if (type == 'Credit card + 3.4%') {
    myprice = myprice * 1.034;
  }

  var price_each = (myprice / quantity);
  document.getElementById("cost").innerHTML = myprice;
  document.getElementById("costeach").innerHTML = price_each;
}

function PHPFMG( formID ){
    var redirect = 'https://www.paypal.me/tim/' + myprice;

1 个答案:

答案 0 :(得分:3)

我建议改为

ISplitCharacters

,然后

function pricecalc() {
  var myprice;
  var a = document.getElementById("field_0");
  var quantity = a.value.substring(0, 1);
  var b = document.getElementById("field_1");
  var type = b.value;

  if (quantity == '2') {
    var rate = '120';
  } else if (quantity == '3') {
    var rate = '110';
  } else {
    var rate = '100';
  }

  myprice = rate * quantity;
  if (type == 'Credit card + 3.4%') {
    myprice = myprice * 1.034;
  }

  var price_each = (myprice / quantity);
  document.getElementById("cost").innerHTML = myprice;
  document.getElementById("costeach").innerHTML = price_each;

  return myprice;
}

这样就不会对全局范围进行规范