制作一个JQuery变量时遇到问题依赖于另一个

时间:2018-03-08 19:12:57

标签: jquery variables

我有一个名为IndependentVar1random的变量,它有两个可能的值(A或B)。如果IndependentVar1random是" A",我希望DependentVar1random等于' a'或者' aa'。 (如果IndependentVar1random是" B",我不希望`DependentVar1random'等于任何东西。)

我尝试了以下代码(以及许多其他迭代),但我无法使其工作:https://jsfiddle.net/ta3og5g3/23/

(我在代码中有问题的部分添加了一个带星号的评论......这是" if"我无法识别的陈述的问题。我&#39 ;我不确定函数是否可以按照我这样做的方式嵌套在另一个函数中。)

HTML

<span class="IndependentVar1randomreplacer">  ///This is what gets replaced by the value of IndependentVar1random
</span>

<span class="DependentVar1randomreplacer"> ///This is what gets replaced by the value of DependentVar1random
</span>

JAVASCRIPT

  $(document).ready(function () {
  function IndependentVarselector1() {
  var IndependentVar1= ['A', 'B'];
    var IndependentVar1random = IndependentVar1[Math.floor(Math.random() * IndependentVar1.length)];
    return IndependentVar1random;  ///EVERYTHING UP UNTIL THIS POINT SUCCESSFULLY GENERATES INDEPENDENTVAR1RANDOM

       if ( IndependentVar1random == A) {  ///**PROBLEM AREA*** THIS DOES NOT GENERATE DEPENDENTVAR1 BASED ON THE INDEPENDENTVAR1RANDOM

                function DependentVarselector1() {
  var DependentVar1= ['a', 'aa'];
    var DependentVar1random = DependentVar1[Math.floor(Math.random() * DependentVar1.length)];
    return DependentVar1random;
}    
}
}

///THE CODE BELOW (SUCCESSFULLY) REPLACES THE SPANS WITH THE VALUES OF THE VARIALBES; NO ISSUE HERE

var IndependentVar1randomreplacer = IndependentVarselector1();  
 $('.IndependentVar1randomreplacer').html(IndependentVar1randomreplacer );

 var DependentVar1randomreplacer = DependentVarselector1();
 $('.DependentVar1randomreplacer').html(DependentVar1randomreplacer );

 });

2 个答案:

答案 0 :(得分:2)

上面的代码有很多问题,下面是简化版本:

function IndependentVarselector1() {
    var IndependentVar1= ['A', 'B'];
    var IndependentVar1random = IndependentVar1[Math.floor(Math.random() * IndependentVar1.length)];
    return IndependentVar1random;
}

function DependentVarselector1(var1) {
    if ( var1 == 'A')
        return null;

    var DependentVar1= ['a', 'aa'];
    var DependentVar1random = DependentVar1[Math.floor(Math.random() * DependentVar1.length)];
    return DependentVar1random;
}

$(document).ready(function () {    
    var IndependentVar1randomreplacer = IndependentVarselector1();  
    $('.IndependentVar1randomreplacer').html(IndependentVar1randomreplacer );

    var DependentVar1randomreplacer = DependentVarselector1(  IndependentVar1randomreplacer );
    $('.DependentVar1randomreplacer').html(DependentVar1randomreplacer );
});

答案 1 :(得分:0)

 if ( IndependentVar1random == A) {

应该是

 if ( IndependentVar1random == 'A') {