【问题标题】:Checking for property on the object passed to jquery tmpl检查传递给 jquery tmpl 的对象的属性
【发布时间】:2012-01-13 13:57:12
【问题描述】:

我有一个这样的示例数据:

data = {opt1: 'One', opt2:'Two', opt3:'Three'};

tmplString = <li>${opt1}</li><li>${opt2}</li>??IF OPT3?? 

$('#node').append(tmplString, data);

在我的tmplString 中,我只想在传入的数据具有名为opt3 的属性时才呈现opt3。如果我使用{{if opt3}},当数据中没有opt3 时会引发错误。有没有办法可以使用 if(prop in obj) 之类的东西。

【问题讨论】:

    标签: jquery jquery-plugins jquery-templates


    【解决方案1】:

    我最近遇到了这个问题,并尝试了 idrumgood 提供的解决方案。不幸的是,在我的情况下,数据可能为空或未定义并且

    typeof null === "object"
    

    所以在值上使用 typeof 不会区分空数据和实际数据,从而导致 jquery 模板出错。我发现如果你使用 $data 模板变量来确定变量的范围,你可以避免这个问题。例如,而不是这个:

    {{if opt3}}<li>${opt3}</li>
    

    使用这个:

    {{if $data.opt3}}<li>${opt3}</li>
    

    这是一个 jsfiddle 演示此解决方案

    【讨论】:

      【解决方案2】:

      你应该可以使用:

      if(typeof opt3 == "string")
      

      或者,如果你里面可能有字符串以外的东西:

      if(typeof opt3 != "undefined")
      

      【讨论】:

      • 你的意思是:"{{if typeof ${opt3} != 'undefined'}}" ?
      • 我不熟悉 jQuery 模板语法,但我拥有的是普通的旧 js,如果可以的话。
      • 如果元素未定义,检查typeof不会引发错误。
      猜你喜欢
      • 1970-01-01
      • 2011-09-20
      • 2019-06-01
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 2019-07-03
      相关资源
      最近更新 更多