我一直在学习一些jquery,现在我想创作一些插件只是为了好玩,我为上传图片写了这个极端插件,我的问题是:我是以正确的方式吗?
插件本身:
$.fn.imageUploader = function (options) {
var options = $.extend(options);
var url = options.url;
this.click(function myfunction() {
var imgId = this.id;
var jqFrmId = "#Frm" + this.id;
var fileId = "File" + this.id;
var jqFileId = "#" + fileId;
//use of title attribute for extra data
var data = $(this).attr("title");
//append a form for each file upload
$("body").append("<form id='Frm" + this.id + "' action='" + url + "?data=" + data + "' method='post' enctype='multipart/form-data'></form>");
//append a input file
$(jqFrmId).append("<input type='file' id='" + fileId + "' name='" + fileId + "' style='display: none;' />");
$(jqFileId).change(function () {
$(jqFrmId).submit(); //upload image
$("form").remove(jqFrmId);
});
$("form").ajaxForm({
success: function (data) {
$("#" + imgId).attr("src", data); //shows image on callback
}
});
$(jqFileId).click();
});
};
如何打电话:
$(document).ready(function ()
{
$(".Image").imageUploader({ url: "Index/UploadImg" }); //or
$("#ImageDetail").imageUploader({ url: "Index/UploadImg" });
})
Html页面如下所示:
<table>
<tr>
<td>1</td>
<td>
<img alt="Front" title="Front" class="Image" id="ImageFront" src="~/Image/NoImage.png" style="width: 100px; height: 100px;" />
</td>
<td>2</td>
<td>
<img alt="Detail" title="Detail" class="Image" id="ImageDetail" src="~/Image/NoImage.png" style="width: 100px; height: 100px;" />
</td>
</tr>
</table>