2015-01-05 48 views
0

当窗体为空或我从中输入新内容时,Div正在工作。和HTML一样显示 - 隐藏在下拉菜单中使用jquery的div但不工作

<select name="product" class="span4" id="product"> 
<option value="4">Article</option> 
<option value="1">Product</option> 
<option value="2">Movie Trailers</option> 
<option value="3">Landing Page</option> 
</select> 

<div class="1 box"> Select Div 1</div> 
<div class="2 box"> Select Div 2</div> 
<div class="3 box"> Select Div 3</div> 
<div class="4 box"> Select Div 4</div> 

的JavaScript:是

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

但是当我去编辑文章或产品这不工作,选择=“选择”一个从数据库类别。瘦不显示DIV默认其选择的div

<select name="product" class="span4" id="product"> 
<option value="4">Article</option> 
<option value="1">Product</option> 
<option value="2" selected="selected">Movie Trailers</option> 
<option value="3">Landing Page</option> 
</select> 

Image Screen Short here

我需要两个功能的选择&无选择的功能。你愿意帮我:)

+0

代码工作正常,在这里http://jsfiddle.net/u920pvx1/很难理解你的要求虽然 – charlietfl

回答

1

如果问题您需要在页面加载时显示与值相关的元素,只需在绑定更改事件处理程序后立即触发更改事件即可。

$('#product').change(function() { 
    $('.box').hide(); 
    $('.' + $(this).val()).show(); 
}).change(); // trigger change so the code inside change handler runs and displays correct eleemnt 

另一个语法同一件事:

$('#product').change(function() { 
    $('.box').hide(); 
    $('.' + $(this).val()).show(); 
}).trigger('change'); 

DEMO

+0

超级老板..很好的解释 – sasi

0

把你的代码变更功能输出就绪

$(document).ready(function(){ 
$('.box').hide(); 
}); 

$('#product').change(function() { 
    $('.box').hide(); 
    $('.' + $(this).val()).show(); 
}); 
+0

你为什么要这样做?如果代码在头部会怎么样?元素在执行时不存在 – charlietfl

+0

准备就绪的代码一旦加载当文档被加载时 – sasi

+0

和外部代码将立即执行,所以如果它在html $('#product')之前会返回没有比赛 – charlietfl

0

的侧面只需出示这样的的document.ready箱:

$(document).ready(function(){ 
$('.box').hide(); 
$('.' + $('#product').val()).show(); 

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