0

好吧,我很确定你可以,除了我的代码现在失败了。

我要告诉我的简短小Javascript程序要做的是,从数组中选择一个代码(我现在已经预设了测试代码 0),然后使用该代码获取该Youtube视频代码的缩略图,以制作一个半自动的Youtube画廊,这意味着我不必进去,手动完成所有繁琐的工作,只需转到视频并将代码复制到数组中,但是,当我尝试将图像的 src 更改为url(变量)通过document.getelementblahblah.src=myVar
我得到控制台错误:Uncaught TypeError: Cannot set property 'src' of null

这是我的代码:

<!Doctype HTML>
<html>
<head>
<script>
var thumbPrefix = "http://img.youtube.com/vi/";
var thumbSuffix = "/mqdefault.jpg";
var vidCode = ['fL01KMMi5_M','6akcfoJ05Aw','lPpot4OCnQs'];
var thumb1Url = thumbPrefix + vidCode[0] + thumbSuffix;
document.write(thumb1Url); //this is just to visualize url
document.getElementById('pie').src=thumb1Url;
</script>
</head>
<body>
<img src="" id="pie" />
</body>
</html>

而且,我也尝试过 setAttribute 方法,所以......

4

4 回答 4

4

“我收到控制台错误: Uncaught TypeError: Cannot set property 'src' of null

那是因为document.getElementById('pie')已经返回null,因为它没有找到具有 id 的元素'pie',因为您的脚本在浏览器解析有问题的元素之前正在运行。

浏览器在遇到脚本块时以脚本块的形式运行代码 - 在文档中从上到下。

将脚本块移动到文档的末尾(例如,就在结束</body>标记之前)或将代码放在名为 onload 的函数中。这样,您的图像元素将被解析并可以从 JS 进行操作。

(您尝试设置变量的事实.src根本不是问题。)

于 2012-10-30T06:34:10.710 回答
0

The reason this is not working is that at the time your code is run, the 'pie' element hasn't been parsed and inserted into the DOM tree yet.

You need to essentially delay the execution of your code until the DOM element you're looking for is completely parsed, so putting that 'script' element just before the closing 'body' tag would solve your issue.

Alternatively, you could also bind an eventHandler to fire when the DOM tree has been parsed. I'd highly recommend going with a library to do this, to help overcome all the cross-browser issues. jQuery is a popular solution, but if you don't wish to include a huge library on your page, this library can help.

于 2012-10-30T06:41:05.023 回答
0

pie当您尝试设置其源时,对象“ ”不存在。该脚本在浏览器遇到时被解析并执行。在您的页面中,首先是脚本,然后是图像标记。您可以按如下方式更正它

<!Doctype HTML>
<html>
<head>
<script>
function setImage(){
    var thumbPrefix = "http://img.youtube.com/vi/";
    var thumbSuffix = "/mqdefault.jpg";
    var vidCode = ['fL01KMMi5_M','6akcfoJ05Aw','lPpot4OCnQs'];
    var thumb1Url = thumbPrefix + vidCode[0] + thumbSuffix;
    //document.write(thumb1Url); THIS IS CAUSING DOCUMENT TO CLEAR OF ALL MARKUP :(
    document.getElementById('pie').src=thumb1Url;
}
</script>
</head>
<body onLoad='setImage'>
<img src="" id="pie" />
</body>
</html>

document.write(thumb1Url)也是造成问题的原因。请尝试Console.log改用调试。

于 2012-10-30T06:34:31.117 回答
0

您的脚本失败,因为它位于文档的头部,并且在加载内容之前执行。像这样放在身体里,效果很好。

<body>

    <img src="" id="pie" />
    <script>
        var thumbPrefix = "http://img.youtube.com/vi/";
        var thumbSuffix = "/mqdefault.jpg";
        var vidCode = ['fL01KMMi5_M','6akcfoJ05Aw','lPpot4OCnQs'];
        var thumb1Url = thumbPrefix + vidCode[0] + thumbSuffix;
        document.write(thumb1Url); //this is just to visualize url
        document.getElementById('pie').src=thumb1Url;
    </script>
</body>
于 2012-10-30T06:35:31.030 回答