【发布时间】:2018-10-15 18:12:44
【问题描述】:
当用户单击按钮时,它会将表单 (#CtrlST) 加载到用户内容 div 中。然后用户填写表单并提交。问题是它无法触发 ctrlst.onsubmit 函数来处理表单数据。当表单被硬编码时,提交函数会很好地触发。但是,动态生成的表单不会。我需要动态生成表单,因为我需要编写的其余代码需要以相同的方式工作。
window.onload = function() {
// Get references to elements on the page.
var StartGB = document.getElementById('StartGB');
var socketStatus = document.getElementById('usercontent');
var ctrlst = document.getElementById('CtrlST');
var mySocket = new WebSocket("ws://0.0.0.0:5678/");
if (StartGB) {
StartGB.addEventListener("click", function (e) {
var gbform = document.getElementById('usercontent');
gbform.insertAdjacentHTML('afterbegin','\n<form class="CST" id="CtrlST" action="#" method="post">\n'+
'<div class="grid-container-plus">\n'+
'<div class="grid-item"><input id="goodreads" name="goodreads" placeholder="Good"></div>\n'+
'<div class="grid-item"><input id="badreads" name="badreads" placeholder="Bad"></div>\n'+
'<div class="grid-item"><button type="submit" class="sbutton">« Start »</button></div>\n'+
'</div>\n'+
'</form>\n');
})
}
if (ctrlst) {
alert('wtf')
// Send a message when the form is submitted.
ctrlst.onsubmit = function(e) {
e.preventDefault();
// Retrieve the message from the Good /Bad form.
var message = good.value + ':' + bad.value;
// Send the message through the WebSocket.
alert(message);
mySocket.send(message);
// Add the message to the messages list.
socketStatus.innerHTML += '<div class="received">' + message + '</div>';
return false;
};
}
};
【问题讨论】:
-
var ctrlst = document.getElementById('CtrlST')的值是多少?它似乎是null,因为只有在您单击StartGB后,具有此id 的表单才会插入到DOM 中。当 DOM 中还没有带有id="CtrlST"的表单时,在窗口加载时评估第二个if条件。
标签: javascript ajax forms websocket