【问题标题】:Uncaught TypeError: Cannot call method 'appendChild' of undefined in Meteor JS未捕获的类型错误:无法在 Meteor JS 中调用未定义的方法“appendChild”
【发布时间】:2014-01-07 15:00:55
【问题描述】:

我尝试在运行时在流星 JS 中提供输入标记,但没有被执行。在这里粘贴我写的代码......当我们创建一个按钮时如何在运行时添加事件......我在执行时遇到错误:Uncaught TypeError: Cannot call method 'appendChild' of undefined,所以请检查代码并建议我该怎么做。等待回复提前谢谢你...

HTML Code :

<head>
  <title>TICTACTOE App</title>
</head>

<body>
  {{> main}}

</body>

<template name="main">
     <h1>Welcome to TICTACTOE App</h1>
    <p><b>Layout Number :</b> <input type="text" id="no" ></p>
</template>

JS Code:

var no;
var newButton;
if (Meteor.isClient)
 {
  // Template.hello.greeting = function ()
  // {
    // return "User Name :";
  // };

  Template.main.events
  ({
    'keydown input#no' : function ()
    {
      // template data, if any, is available in 'this'
      if (event.which == 13) 
        { 
        // 13 is the enter key event
          console.log("You pressed  enter key");
        no = document.getElementById('no');
         if(no.value != '')
         {
           UI();
         }
        }
    }
  });
}
function UI()
{
  console.log("*** UI() ***");
  for(var i = 1 ; i <= no ; i++)
  {
      //TODO:: is there any possibility to add buttons to template at runtime?
      var body = document.getElementsByName('main')[0];
      for(var j = 1 ; j <= no ; j++)
      {
         newButton = document.createElement('input');
         newButton.type = 'button';
         newButton.id = 'btn'+i+j; 
             body.appendChild(newButton);  //here tried by creating a button at runtime      
      }
      var newline = document.createElement('br');
      body.appendChild(newline) 
    }

}
if (Meteor.isServer) 
{
  Meteor.startup(function () 
  {
    // code to run on server at startup
  });
}

【问题讨论】:

    标签: javascript html meteor


    【解决方案1】:

    注意,我不在家,无法在我的开发机器上测试它,但我的猜测是:

    var body = document.getElementsByName('main')[0];
    

    不调用您的 html 中的任何元素,它是您的 Meteor 模板的名称。
    您需要添加一个带有name="main" 的元素,例如

    <template name="main">
         <h1>Welcome to TICTACTOE App</h1>
         <p><b>Layout Number :</b> <input type="text" id="no" ></p>
         <p name="main"></p>
    </template>
    

    【讨论】:

    • 好的,谢谢。但我有一个疑问,即
    • 因为
    猜你喜欢
    • 2013-08-31
    • 2011-11-12
    • 2013-09-14
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多