我真的不明白为什么我遇到这么多小问题。这些问题也在javascript中被注释掉了。非常感谢您的帮助!
1)如何在createNote函数之外获取和使用表单的数据?
2)为什么formArea,textArea和submitButton在单击submitButton时从div1内部消失?
3)出现警报,为什么不是console.log?
4)没有出现控制台日志,为什么?
5)为什么'p'标签不显示在div2中?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Todo App</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<button id="newNote">Add Note</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
的CSS:
#div1 {
width: 200px;
height: 200px;
border: solid 1px #000;
}
#div2 {
width: 200px;
height: 200px;
border: solid 1px #000;
}
的javascript:
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
var newNote = document.getElementById("newNote");
var createNote = function(){
var formArea = document.createElement("form"); formArea.id = "form_1";
var textArea = document.createElement("textarea");
var submitButton = document.createElement("button"); submitButton.innerHTML = "Submit";
formArea.appendChild(textArea);
formArea.appendChild(submitButton);
div1.appendChild(formArea);
var getValue = document.getElementById("form_1").value; // how do I get and use the form's data outside this function?
submitButton.onclick = submitClicked; // why does formArea, textArea and submitButton disappear from inside div1 on the click of submitButton?
};
var submitClicked = function (){
alert("asdf"); // alert is appearing, why is it but not console.log?
console.log("asdf"); // no console log appearing, why?
var paragraphArea = document.createElement("p"); // why isnt this showing up in div2?
div2.appendChild(paragraphArea);
paragraphArea.innerHTML = "asdf";
};
newNote.onclick = createNote;
答案 0 :(得分:0)
当您点击button
内的form
时,form
将自动提交。这意味着页面重新加载。这就是为什么您的自定义元素不断消失以及警报启动的原因。控制台日志已打印,但在刷新后被删除(您可以通过打开Chrome控制台上的“保留日志”功能来验证这一点) )
要处理此问题,请在submitClicked
函数中阻止表单的默认行为。像,
var submitClicked = function(event) {
event.preventDefault();
... Rest of the code.
}