我有這樣的淘汰賽js腳本上傳文件淘汰賽JS:文件上傳事件
此代碼觸發上傳活動當用戶選擇上傳控件文件
Upload.html
$(function() {
var viewModel = {
filename: ko.observable(""),
};
ko.applyBindings(viewModel);
});
<form>
<input id="upload" name="upload"
data-bind="fileUpload: { property: 'filename', url: 'http://localhost/api/upload/PostFormData' }"
type="file" />
<button id="submitUpload">Upload</button>
</form>
FileUpload.js
ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
$(element).after('<div class="progress"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
property = ko.utils.unwrapObservable(options.property),
url = ko.utils.unwrapObservable(options.url);
if (property && url) {
$(element).change(function() {
if (element.files.length) {
var $this = $(this),
fileName = $this.val();
// this uses jquery.form.js plugin
$(element.form).ajaxSubmit({
url: url,
type: "POST",
dataType: "text",
headers: { "Content-Disposition": "attachment; filename=" + fileName },
beforeSubmit: function() {
$(".progress").show();
$(".progressError").hide();
$(".bar").width("0%")
$(".percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + "%";
$(".bar").width(percentVal)
$(".percent").html(percentVal);
},
success: function(data) {
//$(".progress").hide();
//$(".progressError").hide();
// set viewModel property to filename
$("label[for='upload']").text(data);
bindingContext.$data[property](data);
},
error: function(jqXHR, errorThrown) {
$(".progress").hide();
$("div.progressError").html(jqXHR.responseText);
}
});
}
});
}
}
}
現在,我想移動上傳事件觸發的提交按鈕
<button id="submitUpload">Upload</button>
如何做到這一點?現在,這就是我所在的位置,我只是在按鈕的點擊事件中移動上傳事件。但它不起作用,它不會調用API的ajax請求。
$('#submitUpload').click(function() {
if (element.files.length) {
var $this = $(element),
fileName = $this.val();
//alert(element.form);
// this uses jquery.form.js plugin
$(element.form).ajaxSubmit({
url: url,
type: "POST",
dataType: "text",
headers: { "Content-Disposition": "attachment; filename=" + fileName },
beforeSubmit: function() {
$(".progress").show();
$(".progressError").hide();
$(".bar").width("0%")
$(".percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + "%";
$(".bar").width(percentVal)
$(".percent").html(percentVal);
},
success: function(data) {
//$(".progress").hide();
//$(".progressError").hide();
// set viewModel property to filename
$("label[for='upload']").text(data);
bindingContext.$data[property](data);
},
error: function(jqXHR, errorThrown) {
$(".progress").hide();
$("div.progressError").html(jqXHR.responseText);
}
});
}
});
嗨,我不能讓這個工作...在JSFiddle上碰巧有一個工作版本嗎?我收到的元素是未定義的錯誤。我想我可能因爲某些原因放錯了身份證。謝謝 – Thony