[英]Pass a variable directly into getElementById using the parameter (JavaScript)
I'm working on my first JavaScript game and I want to display certain attributes inside of < p> tags. 我正在开发我的第一个JavaScript游戏,我想在<p>标签内显示某些属性。 The ID of each < p> tag will be equal to "show-" and the name of the attribute (see example below for the attribute "name").
每个<p>标记的ID都将等于“ show-”以及属性的名称(关于属性“ name”,请参见下面的示例)。
But I'm having trouble getting the syntax right for getElementById. 但是我无法正确获取getElementById的语法。 Any suggestions?
有什么建议么?
<p id="show-name"></p>
<script>
name = "Bob";
function display(attribute) {
putItHere = "'show-"+attribute+"'"
document.getElementById(putItHere).innerHTML = attribute;
}
display(name);
</script>
You need to target the right element. 您需要定位正确的元素。 Currently you are targeting 'show-Bob' and not 'show-name' what your trying to do.
目前,您的目标是“ show-Bob”而不是“ show-name”。 So first generate the id, from the key
name
and then assign a value to that element. 因此,首先从键
name
生成ID,然后为该元素分配一个值。
var name = "Bob";
function display(key, value) {
var putItHere = "show-"+ key;
document.getElementById(putItHere).innerHTML = value;
}
display('name', name);
note
keep in mind that IDs should be unique within the document note
注意,ID在文档中应该是唯一的
However, other way to do that is to target all elements with a specific tag, for instance 但是,另一种方法是使用特定标签定位所有元素,例如
<div data-id="name"></div>
<div data-id="name"></div>
<div data-id="name"></div>
<script type="text/javascript">
var name = "Bob";
function display(key, value) {
var putItHere = "show-"+ key;
var elements = document.querySelectorAll('div[data-id="'+key+'"]');
for(var eid in elements) {
var element = elements[eid];
element.innerHTML = value;
}
}
display('name', name);
</script>
note
that that this doesn't work in IE7 and below. note
,这在IE7及以下版本中不起作用。
Your attribute is Bob
. 您的属性是
Bob
。 So putItHere = "'show-"+attribute+"'"
is equivalent to: putItHere = "'show-"+"Bob"+"'"
, which makes no sense. 因此
putItHere = "'show-"+attribute+"'"
等效于: putItHere = "'show-"+"Bob"+"'"
,这没有任何意义。
You should get the following error Uncaught TypeError: Cannot set property 'innerHTML' of null
. 您应该得到以下错误
Uncaught TypeError: Cannot set property 'innerHTML' of null
。
This should do: 应该这样做:
function display(attrname, val){
document.querySelector('#show-'+attrname).innerText=val;
}
display("name","Bob");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.