我创建了一个上传方法,通过调用webservice自动从javascript上传文件。由于它是自动上传,我想添加一个删除按钮,以允许用户删除他们上传的文件。所以过程是:
以下是我的javascript代码:
function UploadFiles() {
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var fileData = new FormData();
fileData.append(files[0].name, files[0]);
fileData.append('username', 'Test');
$.ajax({
url: 'MyWebservice.asmx/UploadImages',
type: "POST",
contentType: false,
processData: false,
data: fileData,
dataType: "text",
success: function (response) {
var xmlDoc = new DOMParser().parseFromString(response, "application/xml");
var objElementSuccess = xmlDoc.getElementsByTagName("Success")[0];
var textElementSuccess = objElementSuccess.childNodes[0];
var objElementUpload = xmlDoc.getElementsByTagName("UploadedURL")[0];
var textElementUpload = objElementUpload.childNodes[0];
var tableBody = document.getElementById("Tab_UploadedFiles");
tableBody.style.display = "inline";
var tr = document.createElement('TR');
var tdSuccess = document.createElement('TD');
var tdUploadedFiles = document.createElement('TD');
var tdButtonDelete = document.createElement('TD');
tdSuccess.appendChild(document.createTextNode(textElementSuccess.nodeValue));
tdUploadedFiles.appendChild(document.createTextNode(textElementUpload.nodeValue));
tdButtonDelete.style.textAlign = "center";
// here I am adding the delete button .. what should I do here?
// tdButtonDelete.innerHTML = '<input value ="Delete File" onclick="DeleteUploadedFile()" type="button" />';
tr.appendChild(tdSuccess);
tr.appendChild(tdUploadedFiles);
tr.appendChild(tdButtonDelete);
tableBody.appendChild(tr);
},
error: function (err) { alert(err.statusText); }
});
} else {
alert("FormData is not supported.");
}
}
以下是我的表格:
<table id="Tab_UploadedFiles" class="Tab_UploadedFiles">
<tr>
<th>
File Name
</th>
<th>
Status
</th>
<th>
Delete Uploaded File
</th>
</tr>
</table>
答案 0 :(得分:0)
为特定条目创建表格行时,您可能希望在行的id属性中添加唯一标识符(例如id或名称),如下所示:
<tr data-id="unique_number">
<td>FileName</td>
<td>Status</td>
<td>Delete button</td>
</tr>
这样,您可以听取按钮的on click事件并询问父母的id(在您的情况下是tr元素的id)并使用该ID与Web服务通信要删除的图像。
另一种方法是检查表中tr的索引。然而,这是一种“肮脏”的方式,因为你永远不会100%,这总是正确的。
编辑:
获取data-id,您可以执行以下操作:
var button = [code here to get the button]
$(button).on('click', function(){
var id = $(this).parent().data('id'); //get the parent of the delete button (the tr element) and get the value of the data property 'data-id'
//add the rest of your logic here
});