下拉值选择变量(变量变量)

时间:2011-08-06 15:52:13

标签: jquery drop-down-menu

我有一个下拉框,用于选择要显示的表格。表是字符串变量。我试图应用一些处理变量变量的例子,但我没有运气:-(。I've posted a simplified example here. http://jsfiddle.net/jamesm/mbmxL/

$(document).ready(function () {
   var static_str = "This is the static table...";
   var pppoe_str = "This is the PPPoE table...";
   var dhcp_str = "This is the DHCP table...";
   $('#dropdown').change(function() {
       $("#seltxt").html($(this).val() + "_str" ) ;
   });
});


<form>
 <select id="dropdown" name="dropdown">
  <option value="0" >Choose</option>
  <option value="static" >Static</option>
  <option value="pppoe" >PPPoE</option>
  <option value="dhcp" >DHCP</option>
</select>

   Seltext ...

2 个答案:

答案 0 :(得分:0)

在javascript中,您无法直接将字符串转换为变量名称。在您的情况下,您可以使用如下字典:http://jsfiddle.net/bS2vn/

P.S。我希望我理解正确,但你的问题不明确。下次尝试明确询问您拥有什么,想要什么以及可能出现什么问题。

答案 1 :(得分:0)

试试这个:

<form>
 <select id="dropdown" name="dropdown">
  <option value="0" >Choose</option>
  <option value="static" >Static</option>
  <option value="pppoe" >PPPoE</option>
  <option value="dhcp" >DHCP</option>
 </select>        
</form>

<div id="seltxt"></div>

$(document).ready(function () {
   var str = new Object();
   str.static = "This is the static table...";
   str.pppoe = "This is the PPPoE table...";
   str.dhcp = "This is the DHCP table...";

   // Properties in javascript are just dictionaries in disguise, 
   // javascript is unique on that regard.
   // The above code could be rewritten as: 
   // str["static"] = "This is the static table";
   // str["pppoe"] = "This is the PPPoE table...";

   $('#dropdown').change(function() {
       $("#seltxt").html(str[ $(this).val() ]) ;
   });
});

http://jsfiddle.net/DqdZN/

另一种方法(使用eval,不过是个坏主意,只需像上面那样构建代码):

$(document).ready(function () {
   var str = new Object();
   static_str = "This is the static table...";
   pppoe_str = "This is the PPPoE table...";
   dhcp_str = "This is the DHCP table...";
   $('#dropdown').change(function() {
       $("#seltxt").html( eval( $(this).val() + "_str" ) ) ;
   });
});