尝试做我的第一个Javascript if/else.基本上我想根据从收音机框字段中选择的数字显示DIV.如果选择了选项3,我希望div 1,2和3可见.我显然在某个地方出错了.非常感谢思想/帮助.
<script type="text/javascript" >
$(document).ready(function() {
$("input[name$='supplier']").click(function() {
var test = $(this).val();
if (test=1)
{
$("div.hidesupplier").hide();
$("#suppliersourced1").show();
}
else if (test=2)
{
$("div.hidesupplier").hide();
$("#suppliersourced1").show();
$("#suppliersourced2").show();
}
else if (test==3)
{
$("#suppliersourced1").show();
$("#suppliersourced2").show();
$("#suppliersourced3").show();
}
});
});
</script>
Number of Suppliers:
<label><input name="supplier" type="radio" value="1">1.</label>
<label><input name="supplier" type="radio" value="2">2.</label>
<label><input name="supplier" type="radio" value="3">3.</label>
<div id="suppliersourced1" class="CF hidesupplier" style="display: none;">Supplier One</div>
<div id="suppliersourced2" class="CF hidesupplier" style="display: none;">Supplier Two</div>
<div id="suppliersourced3" class="CF hidesupplier" style="display: none;">Supplier Three</div>
Run Code Online (Sandbox Code Playgroud)
更清洁,更快的版本是:
$("input[name$='supplier']").click(function() {
var test = $(this).val();
$("div.hidesupplier").each(function() {
// get the id of the current supplier, eg: "suppliersourced1"
var myID = $(this).attr('id');
// get the last character and convert it to a number
myID = parseInt(myID.substring(myID.length()-1, 1), 10);
// show all with id less than or eq to test
// hide all with id more than test
if(myID <= test) $(this).show(); else $(this).hide();
});
});
Run Code Online (Sandbox Code Playgroud)
清洁因为你几乎没有重复代码.更快,因为你不盲目地隐藏所有东西并显示特定元素,但只能一次隐藏和显示适当的元素.更快,因为要传输,解析和执行的JS代码字节较少.
| 归档时间: |
|
| 查看次数: |
477 次 |
| 最近记录: |