appendTo()和append()有效,appendChild()不起作用 [英] appendTo() and append() works, appendChild() does not

查看:123
本文介绍了appendTo()和append()有效,appendChild()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为拖放文件上传界面的一部分,当将文件拖放到目标容器上时,会调用showImage. showImage检查文件是否为图像,读取文件,创建新的Image对象,将放置的图像文件的数据设置为src,然后将新元素插入DOM.

As part of a drag-and-drop file upload interface, showImage is called when a file is dropped on the target container. showImage checks that the file is an image, reads the file, creates a new Image object, sets the dropped image file's data as the src, and inserts the new element into the DOM.

对于DOM插入,可以调用jQuery的appendToappend,但是本机方法appendChild返回错误:Uncaught TypeError: undefined is not a function.这是什么原因呢?

For DOM insertion, calling jQuery's appendTo or append works, but the native method appendChild returns the error: Uncaught TypeError: undefined is not a function. What is the reason for this?

var showImage = function(droppedImg) {
    var imageType = /image.*/;

    if (droppedImg.type.match(imageType)) {
        var reader = new FileReader();
        reader.onload = function(e) {
            if (e.target.readyState == FileReader.DONE) {
                newImg = new Image();
                newImg.onload = function(e) {
                    if (e.target.readyState == Image.DONE) {

                        //No DOM insertion. Throws this error: Uncaught TypeError: undefined is not a function
                        var dropTarg = document.querySelectorAll('.drop-container');
                        dropTarg.appendChild(newImg); 


                        //Image inserted into DOM
                        $('.drop-container').append(newImg); 
                        //Image inserted into DOM
                        $(newImg).appendTo('.drop-container'); 

                    }
                };
                newImg.src = reader.result;
            }
        }
        reader.readAsDataURL(droppedImg);
    }
};

推荐答案

querySelectorAll()返回节点列表.要获取第一个元素,请按索引访问它:

querySelectorAll() returns a node list. To get the first element, access it by index:

var dropTarg = document.querySelectorAll('.drop-container')[0];
dropTarg.appendChild(newImg);

一些错误处理,以确保发现可能有问题.

Some error handling to make sure it found something would probably be in order.

这篇关于appendTo()和append()有效,appendChild()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆