【问题标题】:Javascript Function works on a local image but not on a taken image from Ajax requestJavascript 函数适用于本地图像,但不适用于从 Ajax 请求获取的图像
【发布时间】:2017-09-11 13:43:45
【问题描述】:

我正在使用jQuery Zoom 来缩放从 Ajax 请求中获得的图像。因此,让我们从工作示例开始。 当我从文件夹中使用我自己的图像时,它可以完美运行,这意味着我的 js 函数可以缩放它不是问题:

<span class='zoom' id='idImg'>
    <img src='img/me.jpg' width='200' height='200'/>
</span>

这就是我在用户抓取图像时调用缩放的方式:

 <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
    <script src='jquery.zoom.js'></script>
    <script>
        $(document).ready(function(){
            $('#idImg').zoom({ on:'grab' });
        });
    </script>

现在让我们看看它什么时候失败,这就是我获取图片网址的方法:

$.ajax({
        url: "someUrl/getImages.php",
        type: "POST",
        dataType: "json",
        success: function (result) {
            console.log(result)
            $("#idImg").html("<img src="+result["image"]+"width='200' height='200'/>")  
        },
        error: function (response) {
        console.log("error" + response)
    }

所以我从 Ajax 获得的图像完美地打印在 ID IdImg 的 span 上,这意味着 Ajax 请求正在工作,现在唯一失败的是当我尝试抓取图像时它没有缩放。

【问题讨论】:

  • 试试:$("#idImg").html("&lt;img src="+result["image"]+"width='200' height='200'/&gt;").zoom({ on:'grab' }) 我猜处理程序正在被删除,所以你需要重新添加它
  • $.fn.zoom 插件可能不适用于后来添加的元素,它只能在现有的元素上运行。对此你无能为力,除非插件有一个选项,或者你修改插件,或者在元素加载后再次调用插件
  • 尝试将$('#idImg').zoom()放入它自己的方法中,当图像通过success()进来时再次调用它。您正在尝试放大尚未下载的图像。

标签: javascript jquery html ajax


【解决方案1】:

问题是因为在 AJAX 请求之后,在 DOM 中实例化了 zoom()#idImg 的内容不再存在。要解决此问题,您需要在 success 处理程序中的新内容上再次调用 zoom()

success: function (result) {
  $("#idImg").html('<img src="' + result["image"] + '" width="200" height="200" />').zoom({ 
    on: 'grab' 
  });
},

【讨论】:

    猜你喜欢
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2012-07-28
    • 2021-06-18
    • 1970-01-01
    • 2012-02-07
    相关资源
    最近更新 更多