简体   繁体   English

使用Hidden Field Values编写JQuery / Javascript IF / else语句

[英]Writing JQuery / Javascript IF / else statement using Hidden Field Values as

I'm trying to get a div to be assigned a CSS class based on the value of a hidden field that is loaded via ajax. 我试图根据通过ajax加载的隐藏字段的值来为div分配CSS类。

My code returns the proper value for the hidden field when called, but my div is always assigned the same css class, regardless of the result. 调用时,我的代码将为隐藏字段返回正确的值,但无论结果如何,始终为div分配相同的CSS类。

I'm guessing something is wrong with my IF statement syntax: 我猜我的IF语句语法有问题:

function doneLoading(){

var colorStatus = $('#colorStatus').val();

if(colorStatus = 'RED'){
    $('.circleFrame').addClass('redState'); 
}

else if(colorStatus = 'GREEN'){
    $('.circleFrame').addClass('greenState');   
}

else if(colorStatus = 'YELLOW'){
    $('.circleFrame').addClass('yellowState');  
}

else {
    alert("Something is broken");
}
}

It's because you're doing = assignment instead of == comparison. 这是因为您正在执行=分配而不是==比较。 You may want to use http://jshint.com to help locate these sorts of bugs. 您可能需要使用http://jshint.com来帮助查找这些错误。

Consider the following alternative to shorten your code. 考虑以下替代方案以缩短代码。

function doneLoading() {
    var color = $('#colorStatus').val().toLowerCase();
    $('.circleFrame').addClass(color + 'State');
}

To maintain the validation, you could do this: 要维持验证,您可以执行以下操作:

var colors = {green:1, red:1, yellow:1};

function doneLoading() {
    var color = $('#colorStatus').val().toLowerCase();

    if (colors.hasOwnProperty(color))
        $('.circleFrame').addClass(color + 'State');
    else
        alert("Something is broken");
}

You're using the assignment operator instead of the comparison operator. 您使用的是赋值运算符,而不是比较运算符。

Try 尝试

if(colorStatus === 'RED'){
    $('.circleFrame').addClass('redState'); 
}

instead. 代替。 (And similarly for the other colours.) (其他颜色也是如此。)

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

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