我尝试在meteor JS中运行时给出输入标记,但没有执行。粘贴我编写的代码......当我们创建一个按钮时如何在运行时添加事件...并且我在执行时遇到错误:未捕获的TypeError:无法调用未定义的方法'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
});
}
答案 0 :(得分: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>