2012-03-20 55 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>