在JavaScript中使用类(class)而不是ID来选择元素。

huangapple go评论53阅读模式
英文:

Select in javascript with class instead of id

问题

我有这个简单的脚本,用于避免上传大文件。

我需要它能够通过名称或类工作,因为它无法与ID document.getElementById("video573623_upload_field"); 一起使用,因为ID是动态的,这是一个WordPress主题。


英文:

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

&lt;input data-customfile=&quot;custom-upload&quot; /&gt;

Use document.getAttribute(&#39;data-files&#39;)

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

huangapple
  • 本文由 发表于 2023年3月31日 02:48:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定