选项选择,不显示默认值

时间:2016-12-27 16:37:28

标签: jquery html

默认值content1,但不显示“text default show”

请帮帮我..

jQuery(document).ready(function($) {
  jQuery('#select123').change(function() {
    jQuery('.content123').hide();
    jQuery('#' + jQuery(this).val()).show();
  });
});
div.content123 {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select123">
  <option value="content1">content1</option>

  <option value="content2">content2</option>

  <option value="content3">content3</option>
  <option value="content4">content4</option>
</select>
<div id="content1" class="content123">
  text defult show
</div>

<div id="content2" class="content123">
  contentttttttt
</div>
<div id="content3" class="content123">
  content3
</div>
<div id="content4" class="content123">
  content4
</div>

2 个答案:

答案 0 :(得分:1)

默认不显示,因为CSS隐藏了所有DIV。您可以在加载页面时触发select上的点击事件,以便显示默认值。

&#13;
&#13;
jQuery(document).ready(function($) {
  jQuery('#select123').change(function() {
    jQuery('.content123').hide();
    jQuery('#' + jQuery(this).val()).show();
  }).trigger("change");
});
&#13;
div.content123 {
  display: none
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select123">
  <option value="content1">content1</option>

  <option value="content2">content2</option>

  <option value="content3">content3</option>
  <option value="content4">content4</option>
</select>
<div id="content1" class="content123">
  text defult show
</div>

<div id="content2" class="content123">
  contentttttttt
</div>
<div id="content3" class="content123">
  content3
</div>
<div id="content4" class="content123">
  content4
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要将属性selected="selected"添加到要为select设置的选项。 然后在脚本中,您需要显示相应的div

&#13;
&#13;
$(document).ready(function() {
  $('#' + $("#select123").val()).show();
  
  $('#select123').change(function(){
    		$('.content123').hide();
    		$('#' + $(this).val()).show();
    	});
    });
&#13;
div.content123 {
   display: none
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select123">
    	<option value="content1" selected="selected">content1</option>

    	<option value="content2">content2</option>
    	
    <option value="content3">content3</option>
    	<option value="content4">content4</option>
    </select>
    <div id="content1" class="content123">
    	 text defult show
    </div>

    <div id="content2" class="content123">
    	contentttttttt
    </div>
    <div id="content3" class="content123">
    	content3
    </div>
    <div id="content4" class="content123">
    	content4
    </div>
&#13;
&#13;
&#13;