當我嘗試拖放通常由html創建的元素時,一切正常,但是當我嘗試拖放由javascript生成的元素時,返回此錯誤:javascript創建的HTML5拖放元素:
Uncaught TypeError: Cannot read property 'parentNode' of null
我的代碼: JS用於拖放:
<div id="screen">
<div id="menu_items" ondrop="drag(event)" ondragover="allowDrop(event)"></div>
<div id="items1" ondrop="drag(event)" ondragover="allowDrop(event)"></div></div>
<div id="options">
<div class="menu_items1">
<div id="m_div_img10" class="img0" draggable="true" ondragstart="drag(event)"> <img src="./images/example.jpg" alt="example.jpg">
<span class="tooltip"><img src="./images/tip.png"></span></div><div id="m_div_img21" class="img1" draggable="true" ondragstart="drag(event)">
<img src="./images/example.jpg" alt="example.jpg">
<span class="tooltip">
<img src="./images/tip.png">
</span>
</div>
</div>
<div class="items1"></div>
</div>
:由JavaScript生成
var id1;
var name;
function drag(ev) {
name = document.getElementById(ev.target.id).parentNode.id;
ev.dataTransfer.setData("text", name);
id1 = document.getElementById(name).parentNode.id;
}
function drop(ev) {
var id2 = ev.target.id;
if(id1 === id2 + '1'){
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
//Add info to arrays
holders["\"" + id2 + "\": ["].push("{\"place_holder\":\"" + id2 + "\", \"name\":\"" + name + "\"}", ", ");
}
}
function allowDrop(ev) {
ev.preventDefault();
}
HTML示例的生成HTML的方式
例子:
var items = document.createElement('div');
items.id = "options";
document.getElementsByTagName('body')[0].appendChild(items);
var innerDivElem = document.createElement('div');
.
.
.
innerDivElem.id = obj[i][t].name + t;
innerDivElem.className = "img" + t;
innerDivElem.draggable='true';
innerDivElem.setAttribute('ondragstart', 'drag(event)');
inContainerDiv.appendChild(innerDivElem);
我試過了,再次發生同樣的錯誤。以下是我如何設置列表器以及事件的完整輸出 - pastebin.com/FE0HZwJR – emanuilov