简体   繁体   English

Javascript If-else

[英]Javascript If-else

Attempting to do my first bit of Javascript if / else. 尝试做我的第一个Javascript if / else。 Basically I would like to display DIVs according to the number selected from the Radio box field. 基本上我想根据从收音机框字段中选择的数字显示DIV。 If option 3 is selected, I would like div 1, 2 and 3 to be visible. 如果选择了选项3,我希望div 1,2和3可见。 I am clearly going wrong somewhere. 我显然在某个地方出错了。 Thoughts / help is very much appreciated. 非常感谢思想/帮助。

<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>

A cleaner and faster version would be: 更清洁,更快的版本是:

$("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();
    });
});

Cleaner because you have almost no repeating code. 清洁因为你几乎没有重复代码。 Faster because you dont blindly hide everything and show specific elements, but only hide and show appropriate elements in one go. 更快,因为你不盲目地隐藏所有东西并显示特定的元素,但只能一次隐藏和显示适当的元素。 Faster also because there is lesser bytes of JS code to be transferred, parsed and executed. 更快,因为要传输,解析和执行的JS代码字节较少。

在前两个条件中,您有=而不是==。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM