【发布时间】:2012-04-18 06:22:44
【问题描述】:
我正在使用 HAML 和 jquery 来编写我的应用程序。我有一个用于显示 URL 链接的“共享”模板。我希望它灵活,以便根据传入的变量显示不同的 URL。
//Code to trigger view and populate template -> Note I only pass in the thread vara here
share_view = new Onethingaday.Views.Threads.ShareView
thread: new Onethingaday.Models.Thread(@options.thread_muses.first().get('question'))
//snippet from share view to pass the variables to the template
render: ->
$(@el).html @template
nickname: @options.nickname
thread_slug: @options.thread.get('slug')
thread_text: @options.thread.get('text')
@
//Snippet of share view's template. Added if-else statement to check if nickname is defined
.sidebar_text Link:
<% if (typeof <%= nickname %> !== "undefined") { %>
%input.detail_text{value: "<%= 'http://dailymus.es/' + nickname + '/threads/' + thread_slug %>"}
<% } else { %>
%input.detail_text{value: "<%= 'http://dailymus.es/' + '/threads/' + thread_slug %>"}
<% } %>
在上面的例子中,我没有定义“昵称”变量。我希望else部分会被触发并且显示的URL是“http://dailymus.es/threads/some-slug-text”
但是我仍然得到以下内容
如您所见,它仍在触发“if”部分并将“未定义”显示为 URL 的一部分。
在我的情况下,如何正确检查“未定义”变量?
【问题讨论】:
-
也许“昵称”被设置为空?在这种情况下,它的类型将是“对象”而不是“未定义”。
-
当
nickname已经合二为一时,您还需要将<%=%>包装起来吗? -
@dbaseman,我做了一个控制台日志 console.log(typeof @options.nickname) 结果给了我'undefined'
-
你确定条件运算符是 !== 还是 !=
-
@Karthi.L 我都试过了,但都没有用
标签: javascript jquery backbone.js haml undefined