2012-03-20 29 views
0

我有一个项目,我正在研究需要根据选择显示/隐藏一个部门。jQuery在选择框中显示/隐藏 - 动态值

我使用下面的代码作为我的基础:(由此可以看出,在http://jsfiddle.net/rtXLe/工作)

<select> 
    <option value="#divA">a</option> 
    <option value="#divB">b</option> 
</select> 

<div id="divA" class="brandDiv">brand A</div> 
<div id="divB" class="brandDiv">brand B</div> 

<script type="text/javascript"> 
    $(function() { 
     $("select").change(function() { 
      // hide all brands first 
      $("div.brandDiv").hide(); 
      // val is something like #div1 or #div2 
      var targetId = $(this).val(); 
      // show the new selected one 
      $(targetId).show(); 
     }); 
    });   
</script> 

我的问题是,他们是动态创建的选择框中的值不能被改变,参考别的东西,所以他们会:

<select> 
    <option value="3135">a</option> 
    <option value="3136">b</option> 
</select> 

<div id="3135" class="brandDiv">brand A</div> 
<div id="3136" class="brandDiv">brand B</div> 

有了,虽然明明有散列标签从值,然后是不能够被jQuery的拾起丢失。

我需要在jQuery中修改部门的工作?

+0

像这样的事情? var targetId ='#'+ $(this).val(); – mamoo 2012-03-20 08:55:53

回答

2

这是工作:http://jsfiddle.net/jhRHg/5/

HTML:

<select> 
    <option value="3135">a</option> 
    <option value="3136">b</option> 
</select> 

<div id="3135" class="brandDiv">brand A</div> 
<div id="3136" class="brandDiv">brand B</div> 
​ 

JQuery的:

$("select").change(function() { 
    // hide all brands first 
    $("div.brandDiv").hide(); 
    // val is something like #div1 or #div2 
    var targetId = $(this).val(); 

    console.log($(targetId).html()); 
    // show the new selected one 
    $("#"+targetId).show(); 
});​ 

这将帮助,干杯!

0

你只需要手动追加'#'字符。

我已经更新您的jsFiddle为例:

$("select").change(function() { 
    // hide all brands first 
    $("div.brandDiv").hide(); 
    // val is something like #div1 or #div2 
    var targetId = "#" + $(this).val(); // <-- manually appending the # character here 
    console.log($(targetId).html()); 
    // show the new selected one 
    $(targetId).show(); 
});​ 
0

你为什么不添加的哈希?

var targetId = '#' + $(this).val(); 
0

只需手动添加#标签

<script type="text/javascript"> 
    $(function() { 
     $("select").change(function() { 
      // hide all brands first 
      $("div.brandDiv").hide(); 
      // val is something like #div1 or #div2 
      var targetId = $(this).val(); 
      // show the new selected one 
      $("#"+targetId).show(); 
     }); 
    });   
</script>