Javascript 根据选择选项显示div
哦,救命啊,我已经尝试了一百万种不同的方法,但它仍然不起作用:如果从选择/选项框中选择update或final,它应该会显示包含输入字段的div。它只执行switch语句中默认显示的操作。当然,只有在做出选择之后,我才希望它确定是否显示输入字段 在头部部分Javascript 根据选择选项显示div,javascript,jquery,select,hide,show,Javascript,Jquery,Select,Hide,Show,哦,救命啊,我已经尝试了一百万种不同的方法,但它仍然不起作用:如果从选择/选项框中选择update或final,它应该会显示包含输入字段的div。它只执行switch语句中默认显示的操作。当然,只有在做出选择之后,我才希望它确定是否显示输入字段 在头部部分 $(document).ready(function(){ $('#needfilenum').hide(); var optionValue = $("#needtoshow").val(); switch (optionVa
$(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>
你应该调查这件事。将其附加到您的
,然后执行您的逻辑。尝试以下操作:
var selectBox = $("#oldfilenum"), magicDiv = $("#needfilenum");
selectBox.bind("change", function() {
var val = this.value;
if (val === "update" || val === "final") {
magicDiv.show();
} else {
magicDiv.hide();
}
});
当然,您可以改为使用开关
,或者使用具有可接受值的[]
并执行操作。indexOf(val)>-1
或其他操作
正如Victor对另一个答案所评论的那样,
change
在MSIE中触发blur
,因此如果这是一个问题,您可能需要使用另一个,也许mouseup
您可能需要在选择框上绑定一个事件侦听器。()
所以你会有一些大致如下的东西:
$("#oldfilenum").change(function() {
var optionValue = $(this).val();
switch (optionValue) {
case 'update':
$("#needfilenum").show();
break;
case 'final ':
$("#needfilenum").show();
break;
default:
$("#needfilenum").hide();
}
};
检查功能只运行一次,而不是每次更改“选择”字段时都运行。您需要将onchange处理程序放入select字段:
<select id="needtoshow" onchange="your_function_name_here()">
如果要在下拉列表更改时显示和隐藏div,则需要绑定到更改事件,例如:
$(document).ready(function() {
$('#needfilenum').hide();
$('#needtoshow').bind('change', function() {
var optionValue = $("#needtoshow").val();
switch (optionValue)
{
case 'update':
case 'final':
$("#needfilenum").show();
break;
default:
$("#needfilenum").hide();
break;
}
});
});
在您的代码中,switch语句仅在页面首次加载时运行一次。处理更改事件时要非常小心。它们在IE和Firefox中的行为不同(IE会等到blur启动它)。当然,在单选按钮和复选框中,不知道是否也用于选择。谢谢。我没有意识到差异。使用代码格式显示您的代码我想我是按照说明发布的我将重新发布注意:您不能为元素提供id,它们只能被选中、值和标签。。。请参阅w3.org谢谢您的帮助。那是最后的希望。。。看到了,试过了!没有坏习惯,您应该避免内联javascripting。
$(document).ready(function() {
$('#needfilenum').hide();
$('#needtoshow').bind('change', function() {
var optionValue = $("#needtoshow").val();
switch (optionValue)
{
case 'update':
case 'final':
$("#needfilenum").show();
break;
default:
$("#needfilenum").hide();
break;
}
});
});