在某些元素被放入框中并单击提交按钮后,我尝试将它们保存到数组中并将其显示在页面上的另一个段落中。
我已经写了这段代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of HTML5 Drag and Drop</title>
<script type="text/javascript">
function dragStart(e){
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("Text", e.target.getAttribute("id"));
}
function dragOver(e){
e.preventDefault();
e.stopPropagation();
}
function drop(e){
e.stopPropagation();
e.preventDefault();
var data = e.dataTransfer.getData("Text");
e.target.appendChild(document.getElementById(data));
//when i dropped an element and if i made mistake, by clicking on element i remove it from dropbox
var txt1 = document.getElementById(data);
txt1.onclick = function () {
document.getElementById(data).remove();
this.remove();};
}
</script>
<style type="text/css">
#dropBox{
width:150px;
height:auto;
border: 1px solid gray;
background: lightyellow;
text-align: left;
margin: 20px 0;
color: orange;
}
#dropBox{
margin: 10px;
}
</style>
</head>
<body >
<h2>Drag & Drop Demo</h2>
<p>Drag and drop the image into the drop box:</p>
<div id="dropBox" ondragover="dragOver(event);" ondrop="drop(event);"
</div>
<!--for some reason when i drop element in dropbox, it doesn't go in new line, so i wrote this <br>. If you have better solution, please tell me.-->
<label id="dragA" draggable="true" ondragstart="dragStart(event);">Marko
Maric<br></label>
<label id="dragB" draggable="true" ondragstart="dragStart(event);">Ana
Ladic<br></label>
<label id="dragC" draggable="true" ondragstart="dragStart(event);">Ivan Saric<br></label>
<input type='button' onclick='saveAndDisplay()' value='Submit'/>
<!--by clicking on submit button, I want the names i picked to display in this paragraph-->
<p id="demo">"Names are":</p>
</body>
</html>
我试图将元素保存到数组中,但是当我想显示它们时,我得到了这个:[object HTMLLabelElement]。
答案 0 :(得分:0)
你有一些问题。首先,作为Quantastical pointed out,您尚未关闭div#dropBox
代码。
当你这样做时,它会消失,因为它不再包含任何孩子,你已设置height: auto
。我们设置height: 200px
以使其保持打开状态。
现在拖放工作正常,但您的提交按钮会调用saveAndDisplay
,而您尚未为我们定义。我怀疑在您的测试中,您无意中将label
转换为字符串,这会导致[object HTMLLabelElement]
。您要做的就是将每个从#dropBox
移动到新的#demo
父级,即simple:
function saveAndDisplay() {
var result = document.getElementById('demo');
var list = document.getElementById('dropBox');
while (list.children.length > 0) {
result.appendChild(list.children[0]);
}
}
如果你想要四处寻找,那么这是一个working demo。
如果您不想实际移动元素,只需在段落中显示它们,您可以循环它们并构建段落的HTML:
function saveAndDisplay() {
var list = document.getElementById('dropBox').children;
var result = "Names are: <br />";
for (var i = 0; i < list.length; i++) {
result += list[i].innerText + "<br />";
}
document.getElementById('demo').innerHTML = result;
}
以下是该版本的demo。