繁体   English   中英

为什么说元素为空?

[英]Why does it say the element is null?

<p id = "a" onclick = "doThis()">ABCD</p>
function doThis() {
    output = document.getElementById("a");
    alert(output.innerHTML);
    //alert should say ABCD//
}

上面的代码工作正常。 现在,我的问题是,我有多个ID,我想动态更改它们。 我试图通过向doThis()添加参数来做到这一点; 它工作正常,但是当我设置temp = document.getElementById(stringId)并尝试提醒innerHTML时,控制台向我显示一个错误,提示它无法读取innerHTML,并且temp为null。 为什么它不像上面那样起作用?

<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?//

您只需将单击更改为"doThis('a')" ,然后您的代码即可使用。 现在,您没有传递getElementById期望的字符串。

 function doThis(x) { output = document.getElementById(x); console.log(output.innerHTML) } 
 <p id="a" onclick="doThis('a')">ABCD</p> <p id="b" onclick="doThis('b')">EFGH</p> 

这是一个片段,显示您在问题中传递的内容:

 function doThis(x) { console.log(typeof(x)); } 
 <p id = "a" onclick = "doThis(a)">ABCD</p> <p id = "b" onclick = "doThis(b)">EFGH</p> 

如您所见,您正在传递一个对象,而不是字符串。

由于ID的名称不是"a"因此a

尝试这样的事情:

theId = x;
<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>

您需要在引号doThis('a')传递ID

 function doThis(x) { alert(document.getElementById(x).innerHTML); } 
 <p id="a" onclick="doThis('a')">ABCD</p> <p id="b" onclick="doThis('b')">EFGH</p> 

暂无
暂无

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

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