简体   繁体   English

javascript拖放,空容器

[英]javascript Drag and drop, empty container

My goal is to clean any div .create and delete any element inside it before I put the edit link inside it, I have tried but I can't. 我的目标是清理任何div .create并删除其中的任何元素,然后再将其放入编辑链接,但我尝试过,但是不能这样做。 I have this code: 我有以下代码:

http://codepen.io/anon/pen/Ejmemp http://codepen.io/anon/pen/Ejmemp

<div class="edit"><a class="link_edit" id="4545" href="edit.php?id=xxx" ondragstart="drag(event)">edit</a></div>

<div class="create" ondrop="drop(event,this)" ondragover="allowDrop(event)"><a href="create.php?id=xxx" class="link_create">create</a></div>

<div class="create" ondrop="drop(event,this)" ondragover="allowDrop(event)"><a href="create.php?id=xxx" class="link_create">create</a></div>

<div class="create" ondrop="drop(event,this)" ondragover="allowDrop(event)"><a href="create.php?id=xxx" class="link_create">create</a></div>

<div class="create" ondrop="drop(event,this)" ondragover="allowDrop(event)"><a href="create.php?id=xxx" class="link_create">create</a></div>

And this is the javascript: 这是javascript:

function allowDrop(ev){
    ev.preventDefault();                
}

function drag(ev){
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev,container){        
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");  
    /*doesn't work*/
    container.innerHTML = "";  
    /*I write clone because I want to keep the original*/            
    ev.target.appendChild(document.getElementById(data).cloneNode(true));
}

Thank you. 谢谢。

Please note the timing of the edits. 请注意编辑的时间。 The OP has edited in an id , and fixed the TypeError with .innerHTML after my answer was posted. 我的答案发布后,OP在id中进行了编辑,并使用.innerHTML修复了TypeError。


If you check your JS console, you'll probably see a whole bunch of these errors. 如果检查JS控制台,您可能会看到很多此类错误。

"Uncaught TypeError: container.innerHTML is not a function"

This is because .innerHTML is a property, but not a method . 这是因为.innerHTML是属性,而不是方法 You assign to the property. 您分配给属性。

container.innerHTML = '';

Also your draggable element is missing an ID, so 另外,您的可拖动元素缺少ID,因此

ev.dataTransfer.setData("text", ev.target.id);

won't really set anything, which will cause 不会真正设置任何东西,这会导致

ev.target.appendChild(document.getElementById(data).cloneNode(true));

to attempt to clone a null value. 尝试克隆null值。 But you shouldn't be cloning unique elements, regardless. 但是无论如何,您都不应该克隆唯一元素。 (See: ID attribute ) (请参阅: ID属性

Consider rethinking the implementation, and definitely look into unobtrusive JavaScript . 考虑重新考虑实现,并且绝对会考虑使用不引人注目的JavaScript That much inline JavaScript is cumbersome to work with. 这么多的内联JavaScript很难使用。

Some reading material: 一些阅读材料:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM