【问题标题】:How to check if variable is undefined如何检查变量是否未定义
【发布时间】: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 已经合二为一时,您还需要将&lt;%=%&gt; 包装起来吗?
  • @dbaseman,我做了一个控制台日志 console.log(typeof @options.nickname) 结果给了我'undefined'
  • 你确定条件运算符是 !== 还是 !=
  • @Karthi.L 我都试过了,但都没有用

标签: javascript jquery backbone.js haml undefined


【解决方案1】:

你还需要在 中包含昵称吗?

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 2019-05-11
    • 2012-04-28
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2010-09-22
    • 2021-01-31
    相关资源
    最近更新 更多