繁体   English   中英

未捕获的TypeError:无法在流星JS中调用未定义的方法'appendChild'

[英]Uncaught TypeError: Cannot call method 'appendChild' of undefined in Meteor JS

我尝试在运行时在流星JS中提供输入标签,但未执行。 在这里粘贴我编写的代码...当我们创建一个按钮时如何在运行时添加事件...并在执行时出错: Uncaught TypeError:无法调用undefined的方法'appendChild' ,因此请检查代码并建议我该怎么做。 等待回应,谢谢你提前...

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
  });
}

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

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM