简体   繁体   English

无法通过JQuery更改图片的src

[英]Cannot change src of image by JQuery

I am developing ASP.NET MVC 4 application. 我正在开发ASP.NET MVC 4应用程序。 I am trying to change src attribute after controller sent data to a view, however all my attempts have no result. 我试图在控制器将数据发送到视图后更改src属性,但是我的所有尝试都没有结果。 A script at a View: 视图中的脚本:

<script type="text/javascript">
$(document).ready(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        url: '/Home/UploadFiles',
        autoUpload: true,
        done: function (e, data) {
            $('.file_name').html(data.result.name);
            $('.file_type').html(data.result.type);
            $('.file_size').html(data.result.size);             
            $('.file_source').attr('src', 'D:/somePhoto.jpg'); //this row does not set 'src' of <img/>
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('.progress .progress-bar').css('width', progress + '%');
    });
});
</script>

<img class="file_source" src="" /> <!--src attribute is just empty---> 

Could you tell please where I've made an error? 您能告诉我我哪里出错了吗? this row is not working: 该行不起作用:

$('.file_source').attr('src', 'D:/somePhoto.jpg'); //this row does not set 'src' of <img/>

The attribute 'src' of tag is not altered to src="D:/somePhoto.jpg". 标签的属性“ src”不会更改为src =“ D:/somePhoto.jpg”。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Have you tried assigning a valid image location from the web inside the image source? 您是否尝试过通过网络在图像源内部分配有效的图像位置? I am pretty sure, D:\\somePhoto.jpg is the location at server side. 我很确定, D:\\somePhoto.jpg是服务器端的位置。 If that is the case, then javscript does not know how to get it, because js runs on client side, and after you have already sent the data from controller, there is nothing it could do. 如果真是这样,那么javscript不知道如何获取它,因为js在客户端运行,并且在您已经从控制器发送数据之后,它什么也做不了。

First test with an image available from web to test, such as this - http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg 首次测试使用可从网络上获得的图像进行测试,例如: http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg

So change your code to - 因此,将您的代码更改为-

$('.file_source').attr('src', 'http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg');

If that works ( and I am pretty sure, it will), then you know the reason why. 如果那行得通(我很确定,那会行),那么您知道原因。 Just keep the somePhoto.jpg somewhere inside the Content folder of your project and use that url. 只需将somePhoto.jpg保留在项目的Content文件夹中的某个位置,然后使用该URL。

for example 例如

$('.file_source').attr('src', 'http://<hostaddress>/content/image/somePhoto.jpg');

If you are still facing problems, please let me know. 如果您仍然遇到问题,请告诉我。

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

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