【问题标题】:Uncaught TypeError: Cannot read property 'firstChild' of null error message未捕获的类型错误:无法读取空错误消息的属性“firstChild”
【发布时间】:2011-12-03 23:13:54
【问题描述】:

我一直在尝试通过 onChange 事件传递 JS 变量,但一直收到

未捕获的类型错误:无法读取 null 的属性“firstChild”

在谷歌浏览器下。下面是我的代码:

    artistID = album_select.substring(0, album_select.indexOf('/'));
    albumID = album_select.substring(album_select.indexOf('/')+1, album_select.length);     
    var count = 0;
    var tracklist = '';
    for(track in albumlist[albumID][2]){
        count++;
        tracklist+="<option id='"+album+"'>"+track+"</option>";             
        } 
    hstr+="<form><select size='"+count+"' onChange='parent.loadSong(this.value, document.getElementById(\"album_select\").firstChild.nodeValue, document.getElementById(\"artistID\").firstChild.nodeValue)' style='font-size:2em;'>";
    hstr+=tracklist;
    hstr+="</form></select>";

【问题讨论】:

  • 你能显示album_select和artistID的html吗?

标签: javascript xml


【解决方案1】:

这部分字符串:

document.getElementById(\"artistID\")

正在寻找 ID 为"artistID"

我假设您打算连接变量。

"...document.getElementById('" + artistID + "')..."

听起来这个人也需要它:

"...document.getElementById('" + album_select + "')..."

【讨论】:

  • 所以hstr+="&lt;form&gt;&lt;select size='"+count+"' onChange='parent.loadSong(this.value, document.getElementById(\"album_select\").firstChild.nodeValue, document.getElementById(\"artistID\").firstChild.nodeValue)' style='font-size:2em;'&gt;"; 将是hstr+="&lt;form&gt;&lt;select size='"+count+"' onChange='parent.loadSong(this.value, document.getElementById('" + album_select"').firstChild.nodeValue, document.getElementById('" + artistID "').firstChild.nodeValue)' style='font-size:2em;'&gt;";
  • @methuselah:我在评论中误读了您的代码。我不知道,但这似乎就是您想要的,除了 album_select 部分似乎搞砸了。
  • 所以tracks() 函数正在获取一个被album_select 引用的参数。您是否预计页面上的某个元素的 ID 值完全相同?
  • @methuselah:那么在这种情况下,您需要将值连接到字符串中。您上面评论中的代码并没有完全做到这一点。我将更新我的答案以更改那行代码。
猜你喜欢
  • 1970-01-01
  • 2014-04-14
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多