TypeError:document.getElementById(...)为null

时间:2012-12-13 18:03:01

标签: javascript template-engine

我正在尝试使用http://ejohn.org/blog/javascript-micro-templating

构建模板构建器

我的html有这个脚本标记

<script type="text/html" id="item_tmpl">
   <div>
   <div class="grid_1 alpha right">
   </div>
    <div class="grid_6 omega contents">
  <p><b><a href="/<%=AdTitle%>"><%=AdTitle%></a>:</b> <%=AdTitle%></p>
  </div>
 </div>
</script>

<script src="${URLUtils.staticURL('/js/shoptheAd.js')}"type="text/javascript"></script>
The Script contains the following code  
        (function(app){
       if (app) {
       var cache = {};
       this.tmpl = function tmpl(str, data){
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ?
          cache[str] = cache[str] ||
             tmpl(document.getElementById(str).innerHTML) :
          // Generate a reusable function that will serve as a template
          // generator (and which will be cached).
          new Function("obj",
            "var p=[],print=function(){p.push.apply(p,arguments);};" +

            // Introduce the data as local variables using with(){}
            "with(obj){p.push('" +

            // Convert the template into pure JavaScript
            str
              .replace(/[\r\t\n]/g, " ")
              .split("<%").join("\t")
              .replace(/((^|%>)[^\t]*)'/g, "$1\r")
              .replace(/\t=(.*?)%>/g, "',$1,'")
              .split("\t").join("');")
              .split("%>").join("p.push('")
              .split("\r").join("\\'")
          + "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn( data ) : fn;
      };
      var sitecoresuggestions = {
        "suggestions": [
            {
                "AdTitle": "CheckAd",
                "AdDescription": "",
                "AdImageUrl": "http://demo-kiehls.loreal.photoninfotech.com/~/media/Advertisement Images/emma-watson-3.ashx",
                "Count": 2,
                "Hit": 0
            },
            {
                "AdTitle": "CheckAd",
                "AdDescription": "",
               "AdImageUrl": "http://demo-kiehls.loreal.photoninfotech.com/~/media/Advertisement Images/kate2.ashx",
                "Count": 2,
                "Hit": 0
            }
        ]
    } ;
      var show_user = tmpl("item_tmpl"), html = "";
    for ( var i = 0; i < sitecoresuggestions.suggestions.length; i++ ) {
      html += show_user( sitecoresuggestions.suggestions[i] );
    }
         console.log(html);
        } else {
            // namespace has not been defined yet
            alert("app namespace is not loaded yet!");
        }
    })(app);
        When the show_user = tmpl("item_tmpl")  is executed  
      i get the error TypeError: document.getElementById(...) is null

关于调试我已经发现由于某种原因

      <script type="text/html" id="item_tmpl">
      <div>
     <div class="grid_1 alpha right">
     </div>
     <div class="grid_6 omega contents">
    <p><b><a href="/<%=AdTitle%>"><%=AdTitle%></a>:</b> <%=AdTitle%></p>
     </div>
   </div>
   </script>

没有在浏览器中加载任何想法为什么它没有被加载,即使它包含在head标签内或任何其他指针中的错误原因

1 个答案:

答案 0 :(得分:2)

根据帖子:

  

快速提示:浏览器会忽略在页面中嵌入具有未知内容类型的脚本(例如,这里的情况 - >浏览器不知道如何执行text / html脚本) - 以及&gt;搜索引擎和屏幕阅读器。这是一个完美的隐形设备,可以将模板隐藏到&gt;您的页面中。我喜欢将这种技术应用于快速和肮脏的情况,我只需要在页面上使用一些&gt;模板,并且想要一些轻快的东西。

因此页面实际上并不呈现HTML,我认为您只能在页面中引用它,以便您可以提取并应用于其他对象或项目。正如博主所说,你会像以下一样使用它:

var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);