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

답변

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>