如果变量(curBranch)不等于数组中的任何元素(user.subscribed),我想给用户一个'subscribe'按钮,如果不相等,我想给'unsubscribe'按钮.我试过这个:
- if (user != null)
isSubscribed = false
each subscription in user.subscribed
- if (subscription === curBranch)
isSubscribed = true
form(action='/unsubscribe/#{curBranch}')
button(type='submit') Unsubscribe
- if (isSubscribed === false)
form(action='/subscribe/#{curBranch}')
button(type='submit') subscribe
Run Code Online (Sandbox Code Playgroud)
第一部分(换行前)完美运行.但是,在for循环完成之前,jade似乎执行了第三个if语句.
有没有办法让这个顺序运行,或者,我应该使用不同的方法吗?
你应该使用Array.indexOf()而不是循环来做到这一点:
-if (user != null)
-if (user.subscribed.indexOf(curBranch) > -1)
form(action='/unsubscribe/#{curBranch}')
button(type='submit') Unsubscribe
-else
form(action='/subscribe/#{curBranch}')
button(type='submit') subscribe
Run Code Online (Sandbox Code Playgroud)
警告:indexOf IE支持仅附带IE9.如果您正在运行jQuery,则可以使用$.inArray(value, array)或_.contains(list, value)使用underscorejs.