如果陈述与变更有关

时间:2019-03-04 12:17:36

标签: javascript jquery if-statement

我想检查动态值和的变量:

jQuery("select.super-attribute-select").change(function() {
  //console.log("New Product ID: " + this.value);
  var option_id11 = "Yes";
  var option_id12 = "No";
  var selectedvalue = this.value;

  //var optionvalue = "option_id"+selectedvalue;

  if ("option_id" + selectedvalue === "Yes") {
    console.log('hide');
  } else if ("option_id" + selectedvalue === "No") {
    console.log('show');
  } else {
    console.log('Nothing');
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="super_attribute[161]" data-selector="super_attribute[161]" data-validate="{required:true}" id="attribute161" class="super-attribute-select" aria-required="true">
  <option value="">Choose an Option...</option>
  <option value="11">REFURB</option>
  <option value="12">NEW</option>
</select>

,但它始终在控制台中显示 Nothing 。请帮助

2 个答案:

答案 0 :(得分:2)

您不能使用代表该变量名称的字符串来调用变量。尝试创建一个对象来指定值,而不是:

jQuery("select.super-attribute-select").change(function() {
       //console.log("New Product ID: " + this.value);

        var options = {
          option_id11: "Yes",
          option_id12: "No"
        }

        var selectedvalue = this.value;

        var selectedOptionValue = options["option_id"+selectedvalue];

        if (selectedOptionValue === "Yes") {
            console.log('hide');
        } else if (selectedOptionValue === "No") {
            console.log('show');
        } else {
            console.log('Nothing');
        }

    });

答案 1 :(得分:0)

jQuery("select.super-attribute-select").change(function() {
   var data = {
     option_id11:"Yes",
     option_id12:"No"
   }
   var selectedvalue = this.value;
   if (data["option_id"+selectedvalue] === "Yes") {
      console.log('hide');
   } else if (data["option_id"+selectedvalue] === "No") {
      console.log('show');
   } else {
      console.log('Nothing');
   }

});