Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未捕获引用错误:未定义url-JavaScript错误_Javascript_Html_Css - Fatal编程技术网

未捕获引用错误:未定义url-JavaScript错误

未捕获引用错误:未定义url-JavaScript错误,javascript,html,css,Javascript,Html,Css,我试图在每次点击时为背景显示不同的图像。我在数组中包含了一组图像,并尝试使用JavaScript访问它们。但是代码显示错误为 未捕获引用错误:未定义url 我尝试了很多方法来设置url。什么都没用 <body> <div class="arrow right" onclick="channelForward();"></div> <div id="tv"></div> <script> functio

我试图在每次点击时为背景显示不同的图像。我在数组中包含了一组图像,并尝试使用JavaScript访问它们。但是代码显示错误为

未捕获引用错误:未定义url

我尝试了很多方法来设置url。什么都没用

<body>
    <div class="arrow right" onclick="channelForward();"></div>
    <div id="tv"></div>
<script>
    function channelForward(){
    var ch=["F:/html/images/1.jpg",
            "F:/html/images/2.jpg",
            "F:/html/images/3.jpg",
            "F:/html/images/4.jpg"
        ];

    var count=0;
    if(count<ch.length)
    {
    document.getElementById("tv").style.backgroundImage=url("ch[count]");
    count++;
        }
     ````
</script>
</body>
我希望urlch[1]显示image 2.jpg等等。我不熟悉编码,
因此,如果代码中还有其他错误,请给出建议。

您应该从变量中删除引号-

document.getElementById("tv").style.backgroundImage="url(" + ch[count] + ")";

您需要修复变量:

document.getElementById("tv").style.backgroundImage = 'url(' + ch[count] + ')';

我认为这个问题可能是由绝对路径引起的,尽量使用相对路径

var ch=["/html/images/1.jpg",
            "/html/images/2.jpg",
            "/html/images/3.jpg",
            "/html/images/4.jpg"
        ];

打开chrome,F12,Elements,选择,您可以发现是否加载img

您可以使用ES6模板文字添加背景图像,如下所示:


document.getElementByIdtv.style.backgroundImage=`url${ch[count]}` 您的代码存在一些问题

第一:您还没有关闭函数定义的大括号。最后一个右括号}用于if语句的主体

第2点:在脚本块的末尾有4个`。删除这些

第三点:正如elveti指出的那样,您分配的背景不正确。从代码中最简单的方法可能是

document.getElementById("tv").style.backgroundImage=`url(${ch[count]})`;

数字4:每次调用该函数时,count都设置为0,因此背景图像不会改变。有许多可能的解决办法。最简单的方法是在函数外部声明count,使其具有全局作用域。

现在,JS正在尝试调用一个不存在的函数url。你必须把它放在引号里,比如backgroundImage='url'+ch[count]+''