我有16个div: 的 HTML
<table id="table1">
<tr id="tr1">
<td id="divdrag" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="div_content1" draggable="true" ondragstart="drag(event)"><p id="p1">5</p></div></td>
<td id="divdrag" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="div_content2" draggable="true" ondragstart="drag(event)"><p id="p1">11</p></div></td>
<td id="divdrag" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="div_content3" draggable="true" ondragstart="drag(event)"><p id="p1">1</p></div></td>
<td id="divdrag" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="div_content4" draggable="true" ondragstart="drag(event)"><p id="p1">4</p></div></td>
</tr>
...
...
...
<tr id="tr4">
<td id="divdrag" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="div_content13" draggable="true" ondragstart="drag(event)"><p id="p1">12</p></div></td>
<td id="divdrag" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="div_content14" draggable="true" ondragstart="drag(event)"><p id="p1">3</p></div></td>
<td id="divdrag" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="div_content15" draggable="true" ondragstart="drag(event)"><p id="p1">9</p></div></td>
<td id="divdrop" ondrop="drop(event)" ondragover="allowDrop(event)"></td>
</tr>
</table>
我尝试使用此功能对其进行随机播放(页面刷新时) 的 JS
onload = function(){
var parent = document.getElementById('divdrag');
var child = parent.children[1];
var frag = document.createDocumentFragment();
while (child.length) {
frag.appendChild(child[Math.floor(Math.random() * child.length)]);
}
child.appendChild(frag);
}
我哪里弄错了? 看看jsfiddle,因为我不允许发布这么多代码:http://jsfiddle.net/2tESd/1/ 谢谢!
答案 0 :(得分:0)
首先,可能有一个名称相同的ID,所以你
document.getElementById('divdrag');
您需要将它们更改为类
答案 1 :(得分:0)
请在脚本代码中添加以下代码。
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
onload = function(){
var parent = document.getElementById('divdrag');
var child = parent.children[1];
var frag = document.createDocumentFragment();
while (child.length) {
frag.appendChild(child[Math.floor(Math.random() * child.length)]);
}
child.appendChild(frag);
}
希望它有效..