javascript 将函数参数传递给 getElementById "id"
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14349012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass function argument into getElementById "id"
提问by erasmus77
It's a js function that shows various text input forms when you select an apropriate value from a select box.
这是一个 js 函数,当您从选择框中选择合适的值时,它会显示各种文本输入表单。
function arata_formular(formular) {
document.getElementById("formular").style.visibility = "visible";
if(document.getElementById("formular").style.display == "none" ) {
document.getElementById("formular").style.display = "inline";
}
else {
document.getElementById("formular").style.display = "visible";
}
}
But doesn't work as expected. Although it has an argument regardless of what i'll pass into there (lets say arata_formular(entropy) it will still look for the "formular" id not "entropy" one. How can I make the 'inline' insert?
但没有按预期工作。尽管它有一个论点,不管我将在那里传递什么(让我们说 arata_formular(entropy) 它仍然会寻找“formular”id而不是“entropy”id。我怎样才能进行“内联”插入?
Unfortunately I can't use jquery on this or other frameworks. I must use only javascript. Thanks!
不幸的是,我不能在这个或其他框架上使用 jquery。我必须只使用 javascript。谢谢!
回答by Ascherer
Just get rid of the quotes.
只是摆脱引号。
function arata_formular(formular) {
var el = document.getElementById( formular );
el.style.visibility = "visible";
el.style.display = el.style.display === "none" ? "inline" : "visible";
}
OR
或者
function arata_formular(formular) {
document.getElementById( formular ).style = {
visibility: "visible",
display: el.style.display === "none" ? "inline" : "visible"
}
}
回答by Travis J
formular
is a variable but you are using it like a string. Also, you should cache it:
formular
是一个变量,但您像字符串一样使用它。此外,您应该缓存它:
function arata_formular(formular) {
var el = document.getElementById(formular);
el.style.visibility = "visible";
if(el.style.display == "none" ) {
el.style.display = "inline";
}
else {
el.style.display = "visible";
}
return el;//in case you want to use the element
}