简体   繁体   English

使用javascript访问Asp.net mvc4中的图像

[英]accessing the images in Asp.net mvc4 using javascript

I am trying to set an image dynamically at runtime using javascript. 我正在尝试使用javascript在运行时动态设置图像。 However i always get 404 error in firebug saying image could not be found. 但是我总是在萤火虫中收到404错误,提示找不到图片。 when i run this the javascript seems to look for the image in the Home Folder rather than the image folder. 当我运行此脚本时,javascript似乎在主文件夹而不是图像文件夹中查找图像。 Am i missing a format to specify the image urls? 我是否缺少指定图像网址的格式?
Why is it looking at that location whereas it should be looking at Images folder in the solution? 为什么要查看该位置,而应该查看解决方案中的Images文件夹? Also if i make that javascript external the html cannot access it even though my references to the js file are correct. 另外,如果我将JavaScript设为外部,即使我对js文件的引用正确,html也无法访问它。 Anyone willing to contribute on this? 有人愿意为此做出贡献吗? you help be very much appreciated. 非常感谢您的帮助。

Here is my code 这是我的代码

Html HTML

<body onload="startTime();">   

        <div class="img">
             <img id="img1" border="0" src="~/Images/Ghandrukpic4.jpg" alt="GhanddrukPic4" class="image" />
        </div>         

</body>

Javascript Code JavaScript代码

    $(function () {

        function startTime() {

        var imgArray = new Array("Images/60987Ghandruk Village.jpg", "Images/GhandrukPic2.jpg", "Images/ghandrukpic3.jpg");
        var imgCount = 0;
        if (imgCount == imgArray.length) {
            imgCount = 0;
        }
        document.getElementById("img1").src = imgArray[imgCount];
        imgCount++;
        setTimeout("startTime()", 5000);
    }

});

add a / in front of your Images string in the array. 在数组中的Images字符串前添加/

new Array("/Images/60987Ghandruk Village.jpg", "/Images/GhandrukPic2.jpg", "/Images/ghandrukpic3.jpg");

This will let the browser know to request from the root directory of your site. 这将使浏览器知道从您站点的根目录发出请求。 If there is no forward slash it is a Relative path to the page that is loaded. 如果没有正斜杠,则为加载页面的Relative路径。 So if the page you are on is http://yoursite.com/home/ then it will be looking in the images directory nested in your nonexistant /home directory. 因此,如果您所在的页面是http://yoursite.com/home/,则它将在嵌套在您不存在的/ home目录中的images目录中查找。

As far as your javascript. 至于你的JavaScript。 Unwrap your startTime function like so in your external and it should work fine. 像这样在外部中startTime函数,它应该可以正常工作。

function startTime() {

        var imgArray = new Array("/Images/60987Ghandruk Village.jpg", "/Images/GhandrukPic2.jpg", "/Images/ghandrukpic3.jpg");
        var imgCount = 0;
        if (imgCount == imgArray.length) {
            imgCount = 0;
        }
        document.getElementById("img1").src = imgArray[imgCount];
        imgCount++;
        setTimeout("startTime()", 5000);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM