0

我刚刚写了一个小的 if, else if 循环,我unexpected token ';'在控制台中得到一个错误。如果我删除;每个$(this).css('top', top-3"em");语句之后,我会得到另一个错误,说}之前else if是意外的!

这是我的循环,有什么我可能误入歧途的想法吗?

$('div.result').each(function() {

    $(this).css('top', top+"em");
    top = top + 8;

    resultcount = resultcount - 1;

    if(resultcount=5) {
        $(this).css('top', top-3"em");
    } else if(resultcount=4) {
        $(this).css('top', top-7"em");
    } else if(resultcount=3) {
        $(this).css('top', top-14"em");
    } else if(resultcount=2) {
        $(this).css('top', top-20"em");
    } else(resultcount=1) {
        $(this).css('top', top-30"em");
    }

});
4

3 回答 3

3

您正在设置 resultcount var,您没有检查它:

if(resultcount===5) {
    $(this).css('top', "top-3em");
} 
else if(resultcount===4) {
    $(this).css('top', "top-7em");
} 
else if(resultcount===3) {
    $(this).css('top', "top-14em");
} 
else if(resultcount===2) {
    $(this).css('top', top-20"em");
} 
else {
    $(this).css('top', "top-30em");
}

用于===检查结果和类型。

还有很多语法错误,尝试使用开发工具调试它们。

于 2013-05-01T14:32:02.043 回答
2

试试这个你应该在 if 中使用 == 而不是 = 并且你忘记在每个 css 参数中添加 + 。

  $('div.result').each(function() {

        $(this).css('top', top + " em");
        top = top + 8;

        resultcount = resultcount - 1;

        if(resultcount ==5) {
            $(this).css('top', top-3 + "em");
        } else if(resultcount==4) {
            $(this).css('top', top-7 + "em");
        } else if(resultcount==3) {
            $(this).css('top', top-14 + "em");
        } else if(resultcount==2) {
            $(this).css('top', top-20 + "em");
        } 

    });
于 2013-05-01T14:33:17.773 回答
1

您几乎没有语法错误,可能需要在某些地方进行更正。

  • 您需要使用相等运算符===而不是赋值运算符=

  • 您错过了最后一个 if 语句中的 if。

  • 您必须使用来+连接字符串top-3"em"(top-3)+"em"

这是没有语法错误的

现场演示

$('div.result').each(function() {

    $(this).css('top', top+"em");
    top = top + 8;

    resultcount = resultcount - 1;

    if(resultcount===5) {
        $(this).css('top', (top-3)+"em");
    } else if(resultcount===4) {
        $(this).css('top', (top-7)+"em");
    } else if(resultcount===3) {
        $(this).css('top', (top-14)+"em");
    } else if(resultcount===2) {
        $(this).css('top', (top-20)+"em");
    } else if(resultcount===1) {
        $(this).css('top', top-30+"em");
    }    
});
于 2013-05-01T14:32:14.377 回答