当用户单击按钮时,它将表单(#CtrlST)加载到usercontent div中。然后,用户填写表格并提交。问题在于它无法触发ctrlst.onsubmit函数来处理表单数据。对表单进行硬编码后,submit函数会很好地触发。但是,动态生成的表单却没有。我需要动态生成表单,因为我需要编写的其余代码也需要以相同的方式工作。
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;
};
}
};
答案 0 :(得分:0)
实际上,如果将事件附加到DOM,则该DOM对象应该已经可用。因此,您的第一个带有硬编码形式的文件可以正常工作。
对于第二种情况,如果要动态注入与表单相关的DOM,则在注入HTML之后也应附加事件。
如下修改代码,以动态附加提交事件,这将适合您的情况,
window.onload = function() {
// Get references to elements on the page.
var StartGB = document.getElementById('StartGB');
var socketStatus = document.getElementById('usercontent');
var mySocket = null; //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="good" name="goodreads" placeholder="Good"></div>\n'+
'<div class="grid-item"><input id="bad" name="badreads" placeholder="Bad"></div>\n'+
'<div class="grid-item"><button type="submit" class="sbutton">« Start »</button></div>\n'+
'</div>\n'+
'</form>\n');
addSubmitEvent();
})
}
addSubmitEvent();
};
function addSubmitEvent(){
var ctrlst = document.getElementById('CtrlST');
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;
};
}
}
对于这种动态元素事件处理,还有一个称为委托的概念,请仔细阅读以供参考。 如果您使用JQuery,则可以轻松进行委派。