简体   繁体   English

jQuery图像预览不起作用

[英]JQuery Image Preview not working

I've seen several ways to display image preview but none of them seem to work or they work only in FF/Chrome. 我已经看到了几种显示图像预览的方法,但是它们似乎都不起作用,或者仅在FF / Chrome中起作用。

Trying to keep it simple: 尝试保持简单:

Markup: 标记:

<input type="file" id="logo-upload" onchange="changePreview();"/>
<br/>        
<img src='@Url.Image("logo.png")' alt="Preview" id="logo-preview"/>

Javascript: Javascript:

<script type="text/javascript">

    function changePreview() {

        var input = $('#logo-upload').val();

         $('#logo-preview').attr('src', input)
                    .width(150)
                    .height(50);
         }

</script>

When debugging input shows the correct local image path but preview never shows up. 调试input显示正确的本地图像路径,但永远不会显示预览。 Why and how can I get this to work (in all browsers ) ? 为什么以及如何使它在所有浏览器中都能正常工作?

Thanks. 谢谢。

Try setting the $('#logo-upload').change(function(){}) instead of using onChange. 尝试设置$('#logo-upload').change(function(){})而不要使用onChange。 I think that's a good start. 我认为这是一个好的开始。 Then put the jQuery inside $(document).ready(function(){}) . 然后将jQuery放在$(document).ready(function(){}) That could be another issue, if you're setting the script before the elements exist on the page. 如果要在页面上的元素存在之前设置脚本,那可能是另一个问题。

If you can post more code, it would be beneficial. 如果您可以发布更多代码,那将是有益的。

Also, for IE, you're going to run into permissions issues that are on the user, which you don't have control over (at least in this situation). 另外,对于IE,您将遇到用户无法控制的权限问题(至少在这种情况下)。 So, in those cases, you'll either have to upload the image first, to get the image from the server, OR they'll have to change their security settings to allow for this type of content to be accessed. 因此,在这种情况下,您要么必须首先上传图像,然后才能从服务器获取图像,要么他们将不得不更改其安全设置以允许访问此类内容。

<input type="file" id="logo-upload" />
<br/>        
<img src="@Url.Image('logo.png')" alt="Preview" id="logo-preview"/>

<script type="text/javascript">
    $(document).ready(function() {
        $('#logo-upload').change(function() {
            var input = $(this).val();
            $('#logo-preview').attr('src', input).width(150).height(50);
        })
    });
</script>

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

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