Javascript If-else语句

时间:2015-06-04 17:21:54

标签: javascript html css

javascript的新手,但尝试了一个基本的' if,else'陈述并且无法使其发挥作用......

$(function () {
    if ($('.feature:contains("Firmness Rating 1")')) {
    $('#firm').css({'background-image': 'url(firmness1.png)'}).text('Firmness Rating 1');
    }
    if ($('.feature:contains("Firmness Rating 2")')) {
    $('#firm').css({'background-image': 'url(firmness2.png)'}).text('Firmness Rating 2');
    }
    if ($('.feature:contains("Firmness Rating 3")')) {
    $('#firm').css({'background-image': 'url(firmness3.png)'}).text('Firmness Rating 3');
    }
    if ($('.feature:contains("Firmness Rating 4")')) {
    $('#firm').css({'background-image': 'url(firmness4.png)'}).text('Firmness Rating 4');
    }
    if ($('.feature:contains("Firmness Rating 5")')) {
    $('#firm').css({'background-image': 'url(firmness5.png)'}).text('Firmness Rating 5');
    }
    else {
    $('#firm').css({'background-image': 'url(firmness1to5.png)'}).text('Choose your perfect firmness');
 }
 });

我知道必须有更好的方法来做到这一点,请帮助:)

由于

P

2 个答案:

答案 0 :(得分:0)

尝试

$(function () {
    if ($('.feature:contains("Firmness Rating 1")').length) {
        $('#firm').css({'background-image': 'url(firmness1.png)'}).text('Firmness Rating 1');
    }
    else if ($('.feature:contains("Firmness Rating 2")').length) {
        $('#firm').css({'background-image': 'url(firmness2.png)'}).text('Firmness Rating 2');
    }
    else if ($('.feature:contains("Firmness Rating 3")').length) {
        $('#firm').css({'background-image': 'url(firmness3.png)'}).text('Firmness Rating 3');
    }
    else if ($('.feature:contains("Firmness Rating 4")').length) {
        $('#firm').css({'background-image': 'url(firmness4.png)'}).text('Firmness Rating 4');
    }
    else if ($('.feature:contains("Firmness Rating 5")').length) {
        $('#firm').css({'background-image': 'url(firmness5.png)'}).text('Firmness Rating 5');
    }
    else {
        $('#firm').css({'background-image': 'url(firmness1to5.png)'}).text('Choose your perfect firmness');
    }
 });

如果您想要链接多个if语句,请使用else if

另外,要检查jQuery选择器是否能够选择任何元素,请使用$(selector).length,它返回匹配元素的数量。 if(number)返回带有正值的true和带有0或负数的false。因此,如果您的选择器与任何元素匹配,if($(selector).length)将返回true

答案 1 :(得分:0)

请勿在使用ìf时使用它:

if(some condition){
  run code
}
if(some condition){
  run code
}

而是这样做:

if(some condition){
  run code
}
else if( some condition){
  run code
}