简体   繁体   English

如何使用javascript隐藏上传文件元素?

[英]How to hide an upload file element using javascript?

Its quite wierd . 它很奇怪。 My structure is 我的结构是

<form name="fm"> 
    <input type="file" name="fl">
    <input type="text" name="st"> 
</form>

Now document.fm.st.hidden=true; 现在document.fm.st.hidden = true; works as expected hiding the text box but document.fm.fl.hidden=true; 可以像预期的那样隐藏文本框,但document.fm.fl.hidden = true; doesnt works , it doesnt hides the file upload element ! 不起作用,它不隐藏文件上传元素! Why & how to work around ? 为什么以及如何解决?

It sounds like this might be a case of the script running before the page is completely loaded. 听起来这可能是脚本在页面完全加载之前运行的一种情况。 If you want to be absolutely sure that the page is loaded before the script runs, you can do something like this: 如果要绝对确保在脚本运行之前已加载页面,则可以执行以下操作:

document.onload = function(){ // if you want it could also be window.onload
    document.fm.st.hidden = true;
    document.fm.fl.hidden = true;
};

Cant you just give it an id and use 不能只给它一个ID并使用

document.getElementById('yourID');

other whise maybe you can make a css class for it and use Jquery 也许您可以为此创建一个CSS类并使用Jquery

.addClass() and .removeClass()

if you want to keep the input's space than apply visibility = "hidden" otherwise display = "none" . 如果要保留输入的空间,则应用可视性=“ hidden”,否则显示=“ none”

get Element by name var inputElements = document.getElementsByName("fl"); 通过名称获取元素var inputElements = document.getElementsByName(“ fl”); This will provide you a list of the elements which have name 'fl'. 这将为您提供名称为“ fl”的元素的列表。

Now if you want to hide all the elements, run a loop. 现在,如果要隐藏所有元素,请运行循环。 For now, it'll provide only an element. 目前,它仅提供一个元素。 var inputElement = inputElements[0]; var inputElement = inputElements [0];

I would suggest using jQuery if you want to keep using javascript for long. 如果您想长期使用javascript,我建议您使用jQuery。

now hide the element inputElement.style.display = "none"; 现在隐藏元素inputElement.style.display =“ none”;

For starters, make sure your script is after your element. 对于初学者,请确保您的脚本位于元素之后。 The javascript you provided should work as you provided it, but if it doesn't, try the following: 您提供的javascript应该可以像您提供的那样正常工作,但是如果不行,请尝试以下操作:

<form name="fm"> 
    <input type="file" name="fl">
    <input type="text" name="st"> 
</form>

<script>
    // hides the element (it will still take up space)
    document.getElementsByName("fl").style.visibility="hidden";

    // hides the element (it does not take up any space)
    document.getElementsByName("fl").style.display="none";
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM