首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript If-else

Javascript If-else
EN

Stack Overflow用户
提问于 2013-02-01 13:55:49
回答 2查看 511关注 0票数 2

尝试执行我的第一个Javascript if / else。基本上,我希望根据从单选框字段中选择的数字来显示DIVs。如果选择了选项3,我希望div 1、2和3可见。很明显,我在某些方面出了问题。非常感谢您的想法/帮助。

代码语言:javascript
复制
<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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-01 13:57:25

您在前两个条件中使用=而不是==。

票数 4
EN

Stack Overflow用户

发布于 2013-02-01 14:00:40

更干净、更快的版本应该是:

代码语言:javascript
复制
$("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();
    });
});

更干净,因为你几乎没有重复的代码。速度更快,因为您不会盲目地隐藏所有内容并显示特定的元素,而只是一次性隐藏和显示适当的元素。速度更快,因为需要传输、解析和执行的JS代码的字节数更少。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14640601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档