我在此页面上有30个提交按钮,需要标识发送该提交的DOM的ID。这段代码可以正常工作,我现在所需要的只是了解提交的来源。 console.log(“ id =” + this.id);显示id = undefined。
<form id="offspringpicfrm" method="post" enctype="multipart/form-data">
<input id="offspringpicfile" type="file" name="files[]">
<input type="submit" value="Upload File" name="submit" id="offspringpicsubmit" >
</form>
const url = 'pedigree_pic_upload.php';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
console.log("id=" + this.id);
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
答案 0 :(得分:2)
您可以使用e.target
获取有关dom元素的信息:
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
console.log("id=" + e.target.id);
})
<form id="offspringpicfrm" method="post" enctype="multipart/form-data">
<input type="submit" value="Upload File" name="submit" id="offspringpicsubmit" >
</form>