0

我在这里的另一个线程中找到了以下代码来创建 Jquery 下拉菜单:

$(document).ready(function() {
   $('#myselector').change(function(){
      $('.statecontent').hide();
      $('#' + $(this).val()).show();    
   });
});

HTML 看起来像这样

<select id="myselector">
   <option value="state1">State 1</option>
   <option value="state2">State 2 </option>
   <option value="state3">State 3</option>
</select>

<div id="state1" class="statecontent">State1 Specific Page Content Goes here</div>
<div id="state2" class="statecontent">State2 Specific Page Content Goes here</div>
<div id="state3" class="statecontent">State3 Specific Page Content Goes here</div>

这工作得很好,除了一个问题:当页面加载时,它会显示所有三个选项的文本。但是,一旦选择了一个选项,其他文本就会消失,只显示相关文本。为什么加载所有三个选项的文本?如何修复它,以便在用户选择另一个选项之前只显示第一个选项的文本?在此先感谢您的帮助。

4

4 回答 4

1

你可以试试这个:

$(document).ready(function() {

   $('.statecontent').hide();
   $('#' + $('#myselector').val()).show();
   $('#myselector').change(function(){
      $('.statecontent').hide();
      $('#' + $(this).val()).show();    
   });
});

这是工作小提琴

于 2012-08-31T19:59:43.310 回答
1
$(document).ready(function() {
  // this is for the case an option comes selected from server
  showRelatedDiv();

   $('#myselector').change(function(){
       showRelatedDiv();
   });
});

function showRelatedDiv(){
   $('.statecontent').hide();
   $('#' + $('#myselector').val()).show();        
}
于 2012-08-31T19:53:55.673 回答
1

只需在页面加载时触发更改事件,如下所示:

$(function() {
   $('#myselector').on('change', function(){
      $('#' + this.value).show().siblings('.statecontent').hide();    
   }).change();
});​

小提琴

于 2012-08-31T19:55:48.880 回答
0

加载页面后,您需要执行一些处理。您的过滤仅在更改事件发生时启动。

$(document).ready(function() {
   //Hide all states on load
   $('.statecontent').hide();
   //Determine which state is selected and show
   $('#' + $('#myselector').val()).show();

   //Bind the change event.
   $('#myselector').change(function(){
      $('.statecontent').hide();
      $('#' + $(this).val()).show();    
   });
});

工作示例:http: //jsfiddle.net/7cEXZ/

于 2012-08-31T19:55:54.577 回答