JS怎么更换img中src路径

JavaScript013

JS怎么更换img中src路径,第1张

这里采用jquery的(也可以参照改成js的),直接浏览器运行即可执行:

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script type="text/javascript"src="

    <script>

        $(function(){

            $("#img").attr("src","/img/2.jsp")

            //用于前台展示

            $("span").html($("#img").attr("src"))

        })

    </script>

</head>

<body>

  目前路径:<span>/img/1.jpg</span><img id="img" src="/img/1.jpg" />

</body>

</html>

最后那一行有问题。

img.src = "photo[randomnum]"

这样是直接把 "photo[randomnum]"这个字符串赋值给了src。

引号里面是不能放变量的,只会被当作普通字符。

正确的写法应该是:

img.src = photo[randomnum]

不需要引号。