0
我正在使用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 %>"}
<% } %>
在上面的例子中,我没有定义“昵称”变量。我想到的是,其他部分将被触发,显示的URL为“http://dailymus.es/threads/some-slug-text”
但是我仍然得到以下
正如你看到的,它仍然引发了“如果”部分并将“未定义”显示为网址的一部分。
如何在我的情况下正确检查'undefined'变量?
也许“昵称”是越来越设置为空?在这种情况下,它的类型将是“对象”而不是“未定义”。 – McGarnagle 2012-04-18 06:56:26
你还需要在'<%=%>包''nickname'时,它已经在一个? – rkw 2012-04-18 06:59:12
@dbaseman,我做了一个控制台日志的console.log(typeof运算@ options.nickname),结果给了我“未定义” – Zhen 2012-04-18 08:27:05