【发布时间】:2021-08-13 19:30:49
【问题描述】:
我对 document.getElementById() 有疑问。基本上我有不同的表单,每个表单都有不同的 id,我使用一些 Javascript 来替换一些类并在上传后添加动态文件名。
这应该很容易,但我不知道为什么即使 id 是完全唯一的,我也会得到一种奇怪的行为:无论我提交文件的形式是什么,javascript 都会始终在其中的第一个上应用更改。
function spinnerLoad(){
document.getElementById('file-name[[${id}]]').textContent = this.files[0].name;
document.getElementById('spinner[[${id}]]').classList.replace('fas', 'spinner-border');
document.getElementById('spinner[[${id}]]').classList.replace('fa-file-upload', 'spinner-border-sm');
document.getElementById('uploadForm[[${id}]]').submit()
}
/*I'm using Bootstrap for my styling rules*/
/*${id} variable is server-side and it's there to make unique each form, I'm using Thymeleaf template engine*/
<form th:id="'uploadForm'+${id}" method="post" enctype="multipart/form-data" th:action="@{/upload/{id} (id=${id})}">
<label for="file-upload" class="btn btn-outline-success">
<span th:id="'spinner'+${id}" class="fas fa-file-upload"></span> <b>Upload file:</b> <i th:id="'file-name'+${id}">No file selected</i>
</label>
<input id="file-upload" type="file" name="multipartFile" accept="application/pdf" style="display: none" th:onchange="spinnerLoad()"/>
</form>
我用谷歌搜索了这个问题,但我没有找到具体的答案,所以这就是我在这里打扰你的原因。
希望有人能帮我解决这个问题,谢谢。
【问题讨论】:
-
您发布的代码运行良好。您是否尝试在实际元素呈现到页面之前执行它?你说“我试图在输入值更改时触发该代码加载,但它总是以相同的方式运行。”但我不确定你的意思是什么
-
测试了你的代码,它工作正常,你能详细说明你想要完成什么
-
您缺少 css,但代码仍然可以正常工作
-
嗨@Gu160 我试试你的代码,它工作正常这是一个代码示例:jsfiddle.net/rk02qpb5 我刚刚在点击的按钮上应用了一个红色边框。可以分享一下源代码,让我看看吗?
-
感谢您的所有回复,实际上这只是我的问题的一个小代表性示例,而不是我在代码中尝试做的事情。我将上传更新问题的实际代码。
标签: javascript thymeleaf