Javascript 为什么它说元素为空? 函数doThis(){ 输出=document.getElementById(“a”); 警报(output.innerHTML); //警告应该是ABCD// }
上面的代码运行良好。现在,我的问题是,我有多个id,我想动态更改它们。我尝试通过向doThis()添加参数来实现这一点;它工作正常,但是当我设置temp=document.getElementById(stringId)并试图警告innerHTML时,控制台会给我一个错误,告诉我它无法读取innerHTML,并且temp为null。为什么它不能像上面那样工作Javascript 为什么它说元素为空? 函数doThis(){ 输出=document.getElementById(“a”); 警报(output.innerHTML); //警告应该是ABCD// },javascript,Javascript,上面的代码运行良好。现在,我的问题是,我有多个id,我想动态更改它们。我尝试通过向doThis()添加参数来实现这一点;它工作正常,但是当我设置temp=document.getElementById(stringId)并试图警告innerHTML时,控制台会给我一个错误,告诉我它无法读取innerHTML,并且temp为null。为什么它不能像上面那样工作 <p id = "a" onclick = "doThis()">ABCD</p> function doThis
<p id = "a" onclick = "doThis()">ABCD</p>
function doThis() {
output = document.getElementById("a");
alert(output.innerHTML);
//alert should say ABCD//
}
EFGH
函数doThis(x){
theId='“+x+”;
输出=document.getElementById(theId);
//这里我使用alert来测试它。输出和它的innerHTML都是“null”。为什么innerHTML不是ABCD或EFGH//
因为Id的名称不是“a”
它是a
请尝试以下方法:
<p id = "a" onclick = "doThis(a)">ABCD</p>
<p id = "b" onclick = "doThis(b)">EFGH</p>
function doThis(x) {
theId = '"' + x + '"';
output = document.getElementById(theId);
//here I used alert to test it. Both output and it's innerHTML is "null". Why isn't the innerHTML ABCD or EFGH?//
因为Id的名称不是
“a”
它是a
请尝试以下方法:
<p id = "a" onclick = "doThis(a)">ABCD</p>
<p id = "b" onclick = "doThis(b)">EFGH</p>
function doThis(x) {
theId = '"' + x + '"';
output = document.getElementById(theId);
//here I used alert to test it. Both output and it's innerHTML is "null". Why isn't the innerHTML ABCD or EFGH?//
ABCD
EFGH
函数doThis(x){
theId='“+x+”;
输出=document.getElementById(theId);
EFGH
函数doThis(x){
theId='“+x+”;
输出=document.getElementById(theId);
您需要在引号中传递id
doThis('a')
函数完成此操作(x){
警报(document.getElementById(x.innerHTML);
}
ABCD
EFGHEFGH
您需要在引号中传递id
doThis('a')
函数完成此操作(x){
警报(document.getElementById(x.innerHTML);
}
ABCD
EFGH
您只需将单击更改为“doThis('a')”,然后您的代码就可以工作了。现在您没有传递字符串,这正是getElementById
所期望的
函数完成此操作(x){
输出=document.getElementById(x);
log(output.innerHTML)
}
ABCD
EFGH
您只需将单击更改为“doThis('a')”,然后您的代码就可以工作了。现在您没有传递字符串,这正是getElementById
所期望的
函数完成此操作(x){
输出=document.getElementById(x);
log(output.innerHTML)
}
ABCD
EFGH
EFGH
但如果我提醒theId,它会给我“a”。这不是字符串吗?如果是,我不能将它用作id吗?@idonknowanygoodusernames如果传入字符串,则数据类型是字符串。您不需要在其周围加引号将其转换为字符串。此外,当您调用doThis(…)您需要传入一个未执行的字符串。doThis('a')而不是doThis(a),但如果我提醒theId,它会给我“a”。这不是字符串吗?如果是,我可以用它作为id吗?@idontknowanygoodusernames如果传入字符串,则数据类型是字符串。不需要在其周围加引号将其转换为字符串。此外,当调用doThis(…)时,需要传入一个未传入的字符串。doThis('a')而不是doThis(a)我尝试过你的方法,但控制台仍然给我TypeError:无法设置null的属性'innerHTML',我尝试过你的方法,但控制台仍然给我TypeError:无法设置null的属性'innerHTML',typeof是你的朋友!编程快乐!typeof
是你的朋友!编程快乐!
<p id = "a" onclick = "doThis('a')">ABCD</p>
<p id = "b" onclick = "doThis('b')">EFGH</p>
<script type="text/javascript">
function doThis(x) {
theId = '"' + x + '"';
output = document.getElementById(theId);
</script>