错误:无法将属性"src"设置为null [英] Error: Cannot set property 'src' of null

查看:165
本文介绍了错误:无法将属性"src"设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试设置某个元素的来源时,它返回一个错误,并且我不知道为什么它不起作用. 这是javascript:

When I try to set the source of a certain element, it returns an error and I have no clue why this is not working. Here is the javascript:

    function playVid() {
  var videoPlayer = document.getElementById("video");
  var mp4VID = document.getElementById("videoSRC");
  var arrOfVid = ["video/video.mp4","video/video1.mp4"]; //, "video/video2.mp4", "video/video3.mp4"];
  var arrLenVID = arrOfVid.length;
  var randomVID = Math.floor((Math.random() * arrLenVID));
  mp4VID.src = arrOfVid[randomVID]; // mp4VIDSRC.src = arrOfVid[randomVID]
  videoPlayer.load();
  videoPlayer.volume = 0;
  videoPlayer.play();
}
playVid();

其中的HTML部分是:

The HTML part of it is:

<video id="video" autoplay="" style="" muted="">
<source id="videoSRC" src="video/video.mp4" type="video/mp4"> 
    error: unsupported video format
</video>

这是我收到的错误消息:

Here's the error message I'm receiving:

未捕获的TypeError:无法将属性'src'设置为空

Uncaught TypeError: Cannot set property 'src' of null

似乎没有其他东西可以跨越它.

Nothing else seems to cross paths with it.

推荐答案

在加载HTML页面时,浏览器会在页面完全加载之前尝试执行页面顶部的内容.因此,如果您的JavaScript函数调用(playVid();)位于页面顶部,则它会尝试在加载videoSRC之前执行var mp4VID = document.getElementById("videoSRC");.因此mp4VID为null,因此您不能在null对象上设置属性.在这种情况下,您有两个选择.

When an HTML page is loaded, the browser attempts to execute things in the top of the page before the page is completely loaded. So if your javascript function call (playVid();) is at the top of the page, it is trying to execute var mp4VID = document.getElementById("videoSRC"); before the videoSRC is loaded. Therefore mp4VID is null, and you can't set a property on a null object. You have two options if this is the case.

1)将函数调用移到页面底部,紧接html标记之前.

1) move the function call to the bottom of the page, just before the closing html tag.

2)例如,使用jQuery之类的框架并计划在页面加载后执行该函数调用.

2) Use a framework like jQuery and schedule the function call to execute after the page is loaded $(document).ready(playVid); for example.

#2是我的首选方法:

根据我的经验,大多数人都不喜欢视频开始自动播放.

In my experience, most people don't like when videos start to automatically play.

这篇关于错误:无法将属性"src"设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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