未被捕获的TypeError:无法读取null的属性"id" [英] Uncaught TypeError: Cannot read property 'id' of null

查看:88
本文介绍了未被捕获的TypeError:无法读取null的属性"id"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个html5音频播放器.它用于广播电台,因此我需要播放器重新加载源并从"currrentTime = 0;"开始播放当流再次开始时.虽然我在脚本中遇到错误,但我不确定为什么吗?

I'm trying to create an html5 audio player. It's for a radio station, so I need the player to reload the source and start playing from 'currrentTime=0;' when the stream starts again. I get an error in the script though, and i'm not sure why?

我的脚本已运行

错误位置: if(player.id =='paused'){-我收到错误消息:'Uncaught TypeError:无法读取null的属性'id'

Error location: if (player.id == 'paused') { - I get the error: ' Uncaught TypeError: Cannot read property 'id' of null

HTML:

<audio onplay="checkState()" controls="controls" id="paused" src="http://rmceng.radiomaria.ca:8162/;stream.mp3"></audio>

我的JS:

function checkState() {
var player = document.getElementById('player');
var psrc = 'http://rmceng.radiomaria.ca:8162/;stream.mp3';
if (player.id == 'paused') {
    player.currentTime = 0;
    player.src = psrc;
    player.load();
    player.play();
    document.getElementById('player').id = 'playing';
}
else {
    player.pause();
    player.src = "";
    document.getElementById('player').id = 'paused';
    }
}

window.onload = function(){
    checkState();
}

推荐答案

您的标记中没有包含ID播放器的元素.因此,当您告诉JS getElementById时,它什么也找不到.因此,该值将变为"null".之后,调用player.id-与尝试调用不存在的对象的属性ID相同.

You have no element in your markup that has the id player. So when you tell JS to getElementById, it can't find anything. So the value becomes 'null'. After that you call player.id - this is the same as trying to call the property id of an object that doesn't exist.

要解决:给您的播放器属性 id ="player" 或更改选择呼叫.还有其他选择元素的方法.

To fix: Give your player the attribute id="player" or change the selection call. There are other ways to select elements.

document.getElementById(id_string)
document.getElementsByTagName(tag_name)
document.getElementsByClassName("class_values")
document.getElementsByName("name_value")
document.querySelector(css_selector)
document.querySelectorAll(css_selector)

这篇关于未被捕获的TypeError:无法读取null的属性"id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆