【发布时间】:2015-02-22 20:48:38
【问题描述】:
我正在尝试编写自己的评论脚本,方法是使用 javascript 获取输入字段的值,然后使用 document.createElement(Element) 创建一个包含该信息的 div。奇怪的是,当我点击提交表单按钮时,它调用了将 div 附加到 DOM 的 javascript 函数,但随后立即将其删除。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>
<style>
.newComment{
width: 100%;
height: 50px;
background: green;
margin-top: 20px;
}
</style>
<body onload="addElement()">
<form>
<input type="text" name="user" style="margin-top: 20px; font-size: 15px;" placeholder="Username" id="username"></input>
<br />
<br />
<textarea type="text" name="comment" style="width: 100%; height: 100px; font-size: 15px;" placeholder="Comment" id="comment"></textarea>
<br />
<br />
<input type="submit" style="float: left; margin-right: 15%;" onclick="addElement()"></input>
</form>
<script>
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
/*function send(){
var name = document.getElementById("username").value
var comment = document.getElementById("comment").value
console.log(name, comment)
var newDiv = document.createElement('div')
$(newDiv).attr('class', 'newComment')
var divClass = $(newDiv).attr("class")
console.log(divClass)
$(newDiv).appendTo("body")
$(".newComment").html(name)
}*/
</script>
</body>
有人可以解释一下为什么在未注释和已注释函数中都会出现这种情况吗?我已经阅读了 jQuery API,它声称这不应该发生,但每次我使用提交按钮时都会发生这种情况。
谢谢。
【问题讨论】:
-
我认为你不应该两次添加事件处理程序。它可能最终会运行两次......
-
@nus:没有风险,第二个将取代第一个。添加两次是没有意义的。
标签: jquery createelement