英文:
Select in javascript with class instead of id
问题
我有这个简单的脚本,用于避免上传大文件。
我需要它能够通过名称或类工作,因为它无法与ID document.getElementById("video573623_upload_field");
一起使用,因为ID是动态的,这是一个WordPress主题。
var uploadField = document.getElementById("video573623_upload_field");
uploadField.onchange = function() { if(this.files[0].size > 10000){ alert("文件太大!"); this.value = ""; }; };
英文:
I have this simple script that works great to avoid uploading large files.
I need it to work with Name or class because it won't work with ID document.getElementById("video573623_upload_field");
because the ID is dynamic, it's a WordPress theme.
<input type="file" name="files[]" id="video573623_upload_field" class="custom-file-input" multiple="">
<script>
var uploadField = document.getElementById("video573623_upload_field");
uploadField.onchange = function() {
if(this.files[0].size > 10000){
alert("File is too big!");
this.value = "";
};
};
</script>
答案1
得分: 2
尝试 var uploadField = document.getElementsByClassName('custom-file-input')[0];
以前,当您使用 getElementByClassName
时,它返回一个数组的引用变量,然后您直接在该引用数组上使用 onChange()
,可能这就是为什么它不起作用。
getElementById()
直接返回元素,因为 id 总是唯一的。
英文:
Try var uploadField = document.getElementsByClassName('custom-file-input')[0];
Previously when you were using getElementByClassName it was returning a reference variable of array, and then you were directly using onChange() on that reference array, maybe that's why it was not working.
getElementById()
directly returns the element because id is always unique.
答案2
得分: 0
如果您无法在输入中默认使用类名或其他内容,您可以添加自定义属性。自定义属性必须以"data"开头,例如:
<input data-customfile="custom-upload" />
使用 document.getAttribute('data-files')
来获取元素,如果需要的话,您可以获取属性的值。您可以在这里查看更多信息:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
英文:
If you can't use class name or anything by default in the input, you can add a custom attribute the custom attributes have to start whit "data" example
<input data-customfile="custom-upload" />
Use document.getAttribute('data-files')
To get the element also you can get the value of the attribute if you needed, you can see more info here
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论