将Javascript方法“createElement”,“appendChild”,“setAttribute”更改为Jquery

时间:2015-07-15 07:15:24

标签: javascript jquery html

当我尝试将javascript方法createElement,appendChild,setAttribute更改为Jquery时,我遇到了困难。我有一个名为“showThumbnail”的功能,它显示了新上传的img的缩略图。我必须将它的javascript代码更改为JQuery。当我必须替换“getElementById”方法时很容易,但是当我处理“createElement”并且当我尝试向新对象innerHTML及其父对象添加属性时,楼梯就会开始。 这是showThumbnail函数

function showThumbnail(files) {
    var file = files[0]

    //var thumbnail = document.getElementById("thumbnail");
    var $thumbnail = $('#thumbnail').get(0);

    var pDiv = document.createElement("div");
    var image = document.createElement("img");
    var div = document.createElement("div");


    pDiv.setAttribute('class', 'pDiv');
    $thumbnail.appendChild(pDiv);


    image.setAttribute('class', 'imgThumbnail');
    pDiv.appendChild(image)

    div.innerHTML = "X";
    div.setAttribute('class', 'closeDiv');
    pDiv.appendChild(div)

    image.file = file;
    var reader = new FileReader()
    reader.onload = (function (aImg) {
        return function (e) {
            aImg.src = e.target.result;
        };
    }(image))
    var ret = reader.readAsDataURL(file);
    var canvas = document.createElement("canvas");
    ctx = canvas.getContext("2d");
    image.onload = function () {
        ctx.drawImage(image, 100, 100);
    }
}

这就是它在JFIDDLE中的作用:http://jsfiddle.net/r0taz01L/6/

我在想这个

var $image = $("<img>", { class: "imgThumbnail" });
var $pDiv = $("<div>", { class: "pDiv" });        
var $div = $("<div>", { class: "closeDiv" });

$thumbnail.append($pDiv);
$pDiv.append($image);
$pDiv.append($div);

您的想法是什么?

1 个答案:

答案 0 :(得分:1)

我认为应该是这样的。

var $thumbnail = $('#thumbnail').get(0);

var $image = $("<img>", {
    class: "divThumbnail"
});
var $pDiv = $("<div>", {
    class: "divThumbnail"
});
var $div = $("<div>", {
    class: "closeDiv"
}).html('X');

$pDiv.append($image,$div).appendTo($thumbnail);
var reader = new FileReader();
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
reader.onload = function (e) {
    $image[0].src = e.target.result;
}
$image.on('load', function () {
    ctx.drawImage($image[0], 100, 100);
})

Demo