如何在 Javascript 中使用 getElementById 获取动态 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3934366/
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
How do you get a dynamic id with getElementById in Javascript?
提问by seedg
I need to get a dynamic value in the document.getElementById in Javascript.
我需要在 Javascript 中的 document.getElementById 中获取动态值。
However, when I put a variable it does not work, like so:
但是,当我放置一个变量时它不起作用,如下所示:
var = myVar;
myVar = 'test';
document.getElementById(myVar);
How can I implement this?
我该如何实施?
Many thanks
非常感谢
采纳答案by meder omuraliev
It will work properly if you do it after the element has rendered, either by adding it in a callback on window.load, DOM ready, or put the script after the element in the HTML.
如果您在元素呈现后执行此操作,它将正常工作,方法是将其添加到 window.load 的回调中,DOM 就绪,或者将脚本放在 HTML 中的元素之后。
window.onload = function() {
var el = 'bla'; document.getElementById(el).style.display='none';
}
回答by user113716
Your syntax is wrong.
你的语法是错误的。
This:
这个:
var = myVar;
should be:
应该:
var myVar;
So you'd have:
所以你会有:
var myVar;
myVar = 'test';
document.getElementById(myVar);
Then you can place the code in an onload
to make sure the element is available.
然后,您可以将代码放在 an 中onload
以确保该元素可用。
Example:http://jsfiddle.net/kARDy/
示例:http : //jsfiddle.net/kARDy/
window.onload = function() {
var myVar;
myVar = 'test';
var element = document.getElementById(myVar);
alert(element.innerHTML);
};
回答by EMMERICH
Were you supposed to have that equals? It should be:
你应该有平等吗?它应该是:
var myVar = 'test';
document.getElementById(myVar);