为什么说元素为空?

时间:2018-01-12 04:10:56

标签: javascript

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

4 个答案:

答案 0 :(得分:2)

您只需将点击更改为"doThis('a')",然后您的代码即可使用。现在你没有传入一个字符串,这是getElementById所期待的。

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

以下是一段代码,展示了您在问题中传递的内容:

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

如您所见,您传递的是对象,而不是字符串。

答案 1 :(得分:1)

因为ID的名称不是"a",而是a

尝试这样的事情:

theId = x;

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

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