拖放

时间:2015-07-29 09:23:04

标签: javascript html5 drag-and-drop

我想将表格内容拖放到文本框中。

HTML:

<table id = "carTypes">
    <tr><th>Car Type</th><th>Price per mile</th></tr>
    <tr><td carValue = "compact" draggable = "true" >Compact</td><td>$0.99</td></tr>
    <tr><td carValue = "Intermediate" draggable = "true" >Intermediate</td><td>$1.99</td></tr>
    <tr><td carValue = "Luxury" draggable = "true" >Luxury</td><td>$2.99</td></tr>
    <tr><td carValue = "Limo" draggable = "true" >Limo</td><td>$4.99</td></tr>
</table><p>Drag and Drop from the above car-types list to below box: <input type = "text" id = "carTypeChosen" placeholder = 'car type you want' /></p>

JS:

var registerDragDrop = function() {
    var dragSource = document.getElementById("carTypes");

    dragSource.ondragstart = function(event) {
        var dataToCopy = this.getElementsByTagName("td").getAttribute("carValue");
        event.dataTransfer.setData("Text", dataToCopy);
        return true;
    };

    var dropTarget = document.getElementById("carTypeChosen");

    dropTarget.ondrop = function(event) {
        this.value = event.dataTransfer.getData("Text");
        event.preventDefault();
        return false;
    };

    dropTarget.ondragover = function(event) {
        event.preventDefault();
        return false;
    };

    dropTarget.ondragend = function(event) {
        event.preventDefault();
        return false;
    };
};

当我拖放汽车类型时,正在删除空值而不是汽车价值。我不知道我做错了什么。请解释

1 个答案:

答案 0 :(得分:0)

<强> Working Fiddle

您的代码在一些更改后工作,thisdragSource.ondragstart函数返回所有表而不是删除td当您尝试生成错误的getAttribute("carValue")时,这意味着什么因为表格没有carValue attribut,所以请使用返回目标的event.target或在我们的案例中删除td而不是this

此外,您必须在定义后调用您的函数registerDragDrop()

JS更改

替换:

this.getElementsByTagName("td").getAttribute("carValue");

通过:

var dataToCopy = event.target.getAttribute("carValue");

完整JS:

var registerDragDrop = function() {
    var dragSource = document.getElementById("carTypes");

    dragSource.ondragstart = function(event) {
        var dataToCopy = event.target.getAttribute("carValue");
        event.dataTransfer.setData("Text", dataToCopy);
        return true;
    };

    var dropTarget = document.getElementById("carTypeChosen");

    dropTarget.ondrop = function(event) {
        this.value = event.dataTransfer.getData("Text");
        event.preventDefault();
        return false;
    };

    dropTarget.ondragover = function(event) {
        event.preventDefault();
        return false;
    };

    dropTarget.ondragend = function(event) {
        event.preventDefault();
        return false;
    };
};

希望得到这个帮助。