预期声明结束如果

时间:2013-06-05 12:53:02

标签: if-statement asp-classic vbscript

我在表单中设置了以下代码,但我收到了“预期声明”错误。我第一次这样做,并认为我的语法正确,我错过了什么?

            <%
            If Trim(oQuote("shipmeth"))="FREIGHT" Then 
                Response.Write "Freight" 
            ElseIf Trim(oQuote("shipmeth"))="THRSHLD" Then 
                Response.Write "Threshold"
            End If
            %>

4 个答案:

答案 0 :(得分:2)

使用嵌套双向条件时,每个条件必须由其自己的End If关闭:

If condition_A Then
  action_A
Else
  If condition_B Then
    action_B
  Else
    If condition_C Then
      action_C
    Else
      action_D
    End If 'condition_C
  End If 'condition_B
End If 'condition_A

只能使用单个End If关闭n路条件(因为它只是一个条件):

If condition_A Then
  action_A
ElseIf condition_B Then
  action_B
ElseIf condition_C Then
  action_C
Else
  action_D
End If

然而,当你检查不同的条件时,这种n路条件才有意义,例如

If IsEmpty(a) Then
  ...
ElseIf b > 23 Then
  ...

在针对不同的值检查相同的变量时,最好使用Select语句作为Alex K.建议:

Select Case foo
  Case "a"
    'handle foo="a"
  Case "b", "d"
    'handle foo="b" as well as foo="d"
  Case Else
    'handle non-matches
End Select

答案 1 :(得分:1)

我认为“否则if”应该是一个词,例如elseif

答案 2 :(得分:1)

If之后的第一个语句必须在新行上;

If Trim(oQuote("shipmeth"))="FREIGHT" Then 
  Response.Write "Freight" 

以下条件可以在同一行,但必须使用ElseIf

ElseIf Trim(oQuote("shipmeth"))="THRSHLD" Then Response.Write "Threshold"
ElseIf ...

我建议一个更易读的案例;

select case Trim(oQuote("shipmeth"))
    Case "THRSHLD"
        Response.Write "Threshold"
    Case "PREMTHRHLD"
        Response.Write "Premium Threshold"
    ...
end select

这样做的另一个好处就是只执行一次Trim(oQuote("shipmeth"))

答案 3 :(得分:0)

你在这里有很好的答案,我会附加一个(轻微优化的)替代品。

strTest   = Trim(oQuote("shipmeth"))
strResult = "Unexpected"
If strTest ="FREIGHT" Then strResult = "Freight"
If strTest ="THRSHLD" Then strResult = "Threshold"
Response.Write strResult

修改

为了澄清我的想法,我讨厌嵌套If..Then,遗憾的是在VBScript中没有GoTo Label,因此上面的双重比较可以用函数进行优化。

strResult = "Unexpected"
MyResponse Trim(...), strResult
Response.Write strResult

Sub MyResponse(strIn, strOut)
    If strIn = "FREIGHT" Then
        strOut = "Freight" : Exit Sub
    End If
    If strIn = "THRSHLD" Then strOut = "Threshold"
End Sub
相关问题