JQuery可拖动动态与document.createElement

时间:2014-03-24 12:34:13

标签: javascript jquery html draggable

我希望能够动态创建div并使用JQuery使div可拖动。 如果我使用JQuery选择器,该元素将变为可拖动。如果我创建一个div然后在div上调用draggable()它不起作用。来自控制台的错误状态"布尔值不是函数"。

   var LoadImage = {

handleFileSelect: function(evt)
{
     var files = evt.target.files; // FileList object

     // files is a FileList of File objects. List some properties.
     var output = [];
     for (var i = 0, f; f = files[i]; i++) {
     output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
              f.size, ' bytes, last modified: ',
              f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
              '</li>');


    LoadImage.getBinary64DataFromFile(f);
}
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';

},
getBinary64DataFromFile: function(file)
{
     var reader = new FileReader();

       reader.onload = function(e) {
       var dataURL = reader.result;
       //alert(dataURL);
       LoadImage.createImageFromBinary64(dataURL);
    }

       reader.readAsDataURL(file);

},
createImageFromBinary64: function(b64)
{
    var image = new Image();
    image.src = b64;
    image.onload = function(){

       LoadImage.createCanvasForImage(image);
    };
},
createCanvasForImage: function(image)
{

    var canvas = document.createElement("canvas");
    canvas.setAttribute("width", "200px");
    canvas.setAttribute("height", "200px");
    canvas.setAttribute("id","myCanvas");
    //canvas.width = 200;
    //canvas.length = 200;  
    var context = canvas.getContext('2d');
    context.drawImage(image,0,0, 200, 200);

    var div = document.createElement('div');
    div.setAttribute('id','draggable');
    div.setAttribute('class','ui-widget-content');
    div.appendChild(canvas);
    div.draggable();  // this is what I want to be able to do
    var content = document.getElementById('content');
    content.appendChild(div);

    //LoadImage.makeDraggable();  // this works

},
makeDraggable: function()
{

   $( "#draggable" ).draggable();

}

};

1 个答案:

答案 0 :(得分:2)

变量div只是一个DOM元素。要在其上调用jQuery方法,您需要将其包装在jQuery包装器中。以下一行:

div.draggable();

应该是:

$(div).draggable();