繁体   English   中英

使用javascript分配动态变量

[英]Use javascript to assign a dynamic variable

我有这段代码可用于更改具有相同结尾ID的不同下拉列表。 我在其他地方为rl和rl_extra分配了变量rs和rs_extra。

var前缀将与这两个rl或rs中的on一起返回。 然后,我想检查rl是否等于值,但是我需要通过前缀调用rl变量。

因此,如果前缀==“ rl”,则rl和rl_extra变量在前缀中为rl。 同样,如果前缀==“ rs”,则显示的rl变量实际上是rs和rs_extra。

有没有办法分配变量变量?

$('[id$="_prop_val"], [id$="_extra_val"]').change(function(){
    var prefix = this.id.slice(0,2);
    if(  rl == $('#'+prefix+'_prop_val').val() 
         && rl_extra == $('#'+prefix+'_extra_val').val()){
        $('#'+prefix+'_nt_row').hide();
    }
    else{
        $('#'+prefix+'_nt_row').show();
    }
    getPrices();
    displayNMP();
});

如果我理解您的意思,则可以执行以下操作:使用具有属性的对象代替rl,rl_extra,rs,rs_extra等。

var props = {
    "rl": rl, // Or you could use the selector directly here and skip the rl declaration entirely
    "rl_extra": ...,
    "rs": ...,
    "rs_extra": ...,
    "xy": ...,
    "xy_extra": ...,
    ...
};

接着:

$('[id$="_prop_val"], [id$="_extra_val"]').change(function() {
    var prefix = this.id.slice(0,2);
    if (props[prefix] == $('#'+prefix+'_prop_val').val() && props[prefix + "_extra"] == $('#'+prefix+'_extra_val').val()) {
        $('#'+prefix+'_nt_row').hide();
    } else {
        $('#'+prefix+'_nt_row').show();
    }
    getPrices();
    displayNMP();
});

您将要使用data-* HTML元素属性。

jQuery .data()函数: http : //api.jquery.com/data/
进一步阅读: https : //developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

因此,您的JS代码如下所示:

$(".dropdown").change(function(){

  var associated_element = $('#'+this.data("associated-id"));
  var associated_value_to_match = this.data("associated-value");

  if (associated_element.val() == associated_value_to_match)
    associated_element.hide();
  else
    associated_element.show();

  getPrices();
  displayNMP();

}

而且您的HTML代码如下所示:

<select class="dropdown" id="first" data-associated-id="second" data-associated-value="2">
</select>
<select class="dropdown" id="second" data-associated-id="third" data-associated-value="3">
<option value="1">one</option>
<option value="2">two</option>
</select>

对于您要完成的工作,我有些朦胧,但是以上内容应该为您提供如何将元数据与HTML元素相关联的要点,并且可以在JS逻辑中使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM