如何在另一个JavaScript脚本中使用JavaScript变量?

时间:2019-01-16 21:40:32

标签: javascript html

因此,在代码的较早部分中,我在标记内将变量charge的值设置为其他链接。

如何在更高版本的javascript中使用此变量的值,因为'url:charge'不起作用。我需要写不同的变量吗?

“网址:chargesilver.php”有效,但“网址:charge”无效。

<script>

function setmembershipayment(){
    if (usermembershipchoice == "Silver") {
        var charge = "chargesilver.php";
        alert(charge);
    } else if (usermembershipchoice == "Gold") {
        var charge = "chargegold.php";
        alert(charge);
    } else if (usermembershipchoice == "Platinum") {
        var charge = "chargeplatinum.php";
        alert(charge);
    } else { 
       alert("ERROR");
    } // THE MISSED BRACKED!! ;)
}
</script>

<script>
    $.ajax({
                  type: "POST",
                  url: charge,
                  data: form.serialize(),
                  success: function(response){
 </script>

3 个答案:

答案 0 :(得分:0)

收费不是全球性的。

它的作用域在函数之内

在函数外部声明

var charge = ''

function setmembershipayment(){
    ....

样品

<script>

var charge = ''

function setmembershipayment(){
  if (usermembershipchoice == "Silver") {
    charge = "chargesilver.php";
    alert(charge);
  } else if (usermembershipchoice == "Gold") {
    charge = "chargegold.php";
    alert(charge);
  } else if (usermembershipchoice == "Platinum") {
    charge = "chargeplatinum.php";
    alert(charge);
  } else { 
   alert("ERROR");
 } // THE MISSED BRACKED!! ;)
}

 setmembershipayment()

 $.ajax({
     type: "POST",
     url: charge, // OR Just return it from the function here and make sure there is a default value
     data: form.serialize(),
     success: function(response){
</script>

或只需从函数返回它,并确保有默认值

答案 1 :(得分:0)

最简单的方法是使函数返回您要使用的费用。

function getMembershipPayment(){
    if (usermembershipchoice == "Silver") {
        return "chargesilver.php";
    } else if (usermembershipchoice == "Gold") {
        return "chargegold.php";
    } else if (usermembershipchoice == "Platinum") {
        return "chargeplatinum.php";
    } else { 
       alert("ERROR");
       return "some default value"
    } // THE MISSED BRACKED!! ;)
}

$.ajax({
  type: "POST",
  url: getMembershipPayment() // returns the value of charge,
  data: form.serialize(),
  success: function(response){}
})

答案 2 :(得分:0)

也许从 time id num 0 2018-01-01 01:00:00 A 2 1 2018-01-01 02:00:00 A 3 6 2018-01-03 09:00:00 B 12 7 2018-01-03 10:00:00 B 13 8 2018-01-03 11:00:00 B 14 9 2018-01-03 12:00:00 B 15 11 2018-05-30 00:00:00 C 122 12 2018-05-30 01:00:00 C 133 13 2018-05-30 02:00:00 C 144 14 2018-05-30 03:00:00 C 155 调用函数以返回正确的字符串值。也许使用switch代替if / else结构,因为它更容易阅读。

url