从文件上传元素向js函数发送'this'

时间:2014-07-30 07:25:16

标签: javascript

我正在上传图片。 onClick一个可见按钮,它触发隐藏的输入表单(它是隐藏的,因为它很难看),它要求用户选择一个文件。当做出选择时,它会触发onChange="imagePreview(this);"函数,然后使用'this'元素。

function imagePreview (this) {
   var files = this.files;
   var file = files[0];
   ...
}

我要做的是摆脱html元素中onChange="imagePreview(this);"的插入,所以我需要以某种方式从javascript或jQuery中调用这个元素。有人可以给我一个暗示。

3 个答案:

答案 0 :(得分:2)

只需获取元素并使用 addEventListener 或jQuery的 .change 方法来设置事件监听器

HTML

<input type="file" id="myfile" />

JS

function imagePreview(){
   //The context of the function will
   //be the element that triggered it
   var files = this.files;
   var file = files[0];    
}

var fileCtrl = document.getElementById("myfile");
fileCtrl.addEventListener("change",imagePreview);
//jQuery
$("#myfile").change(imagePreview);

jQuery .change

addEventListener

答案 1 :(得分:0)

您可以通过jQuery附加事件监听器,

$(function() {
    $("that.input").change(imagePreview); 
    //this will send this as parameter to imagePreview function
});

答案 2 :(得分:0)

不要在函数中传递this参数,否则它会指向window

function imagePreview (elem) {
   var files = elem.files;
   var file = files[0];
   ...
}

现在,使用绑定事件的this

onChange="imagePreview(this)"
相关问题