根据选择选项显示 div
哦,救命,我已经尝试了一百万种不同的方法,但它仍然不起作用:如果您从选择/选项框中选择更新或最终,它应该显示其中有输入字段的 div。它只执行 switch 语句中默认显示的操作。当然,只有在做出选择之后,我才希望它确定是否显示输入字段。
在头部部分...
$(document).ready(function(){
$('#needfilenum').hide();
var optionValue = $("#needtoshow").val();
switch (optionValue)
{
case 'update':
$("#needfilenum").show();
break;
case 'final':
$("#needfilenum").show();
break;
default:
$("#needfilenum").hide();
break;
}
});
//});
'<select id="needtoshow" >
<option id="dfaut" value="0">Select Something</option>
<option id="update" value="update">Update</option>
<option id="final" value="final">Final</option>
<option id="allergy"value="allergy">Vegan</option>
</select>
<div id="needfilenum" style="background:#f00;">
<input type="text" name="wharever" />
</div>
我可以更改开关上的默认设置,这似乎决定了它显示的内容 也尝试过
// $("#needtoshow").change(function() {
// switch ($(this).val())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你想让div在下拉菜单发生变化时显示和隐藏,你需要绑定到change事件,例如:
在你的代码中,switch语句只在页面第一次加载时运行一次。
If you want to have the div show and hide when the drop-down changes, you need to bind to the change event, for example:
In your code, the switch statement runs only once when the page first loads.
您可能想在选择框上绑定一个事件侦听器。 (更改事件)
所以你会得到类似的东西:
You probably want to bind an event listener on your select box. (change event)
So you would have something along the lines of:
尝试这样的事情:
当然,您可以使用
switch
代替,或者使用[]
可接受的值并执行it.indexOf(val) > -1
或其他。正如 Victor 对另一个答案的评论,
change
在 MSIE 中触发blur
,因此您可能需要使用另一个 事件 如果这是一个问题,也许是mouseup
。Try something like this:
Of course you can use
switch
instead, or have a[]
of acceptable values and doit.indexOf(val) > -1
or whatever.As Victor commented on another answer,
change
fires onblur
in MSIE, so you may want to use another event if that is an issue, perhapsmouseup
.您应该查看 change() 事件。将其附加到您的
You should look into the change() event. Attach that to your
<select>
and then perform your logic.您的检查函数仅运行一次,而不是每次更改选择字段时运行。您需要将 onchange 处理程序放入选择字段中:
Your checking function runs only once, and not every time you change the select field. You need to put an onchange handler into the select field: