【问题标题】:Replace image on button click单击按钮时替换图像
【发布时间】:2017-03-03 11:26:07
【问题描述】:

我正在尝试替换按钮单击时的图像,但我似乎没有弄清楚。我从我的 ajax 值中从我的服务器获取了一个看起来像 photo/1583testImg.png 的图像。我现在不想用我通过 ajax 从服务器获取的照片替换当前照片。

 for(file in search){
    var title = search[file].title;
    var photo = search[file].path;
    $(".search-result:first").clone().appendTo(".search").find("h3").text(title);
    $(".search-result:first").clone().appendTo(".search").find("src").replace(photo); // this is the codeline that doesn't work
    console.log(title+"+"+photo);
}

【问题讨论】:

  • 为什么要克隆两次?
  • 嗯,好问题,我想我可以克隆一次

标签: javascript jquery html ajax


【解决方案1】:

你应该改变:

$(".search-result:first").clone().appendTo(".search").find("src").replace(photo);

到:

$(".search-result:first").clone().appendTo(".search").attr("src",photo);

如果需要显示完整路径,可以使用一些选项:

//window.location.host //you'll get sub.domain.com:8080 or sub.domain.com:80
//window.location.hostname ////you'll get sub.domain.com
//window.location.protocol : you'll get http:
//window.location.port //you'll get 8080 or 80
//window.location.pathname //you'll get /virtualPath

var mainUrl =  window.location.protocol+"//"+window.location.hostname;

$(".search-result:first").clone().appendTo(".search").attr("src",mainUrl+"/img/"+photo);

这会给你http://example.com/img/photo/1583testImg.png

【讨论】:

  • 哦,是的,这行得通,我能再问一件事吗,因为我从服务器获取照片,我如何实际显示它,因为我从照片所在的服务器获取路径,如photo/testImg.png。 Surley 我不能把它添加到 srcs 中吗?
  • 你想显示完整路径吗?类似http://example.com/img/photo/testImg.png 而不是photo/testImg.png
  • 嗯,这可能可行,因为我可以使用 url 在我的浏览器上查看它。但似乎只添加attr("src","http://example.com/img/"+photo);
  • 是的,你可以,我用解决方案编辑了答案,编辑到你自己的结构
  • 是的,我在我的服务器上尝试了这个(即启动并运行,可以通过 url 查看图像)我试图将它粘贴到 html 中并且它有效,但是 appendTo 并只是附加新图片没有像clone.appendTo(".search").attr("src", "http://www.mindshiftinteractive.com/wp-content/uploads/2016/10/test-big.png");那样工作(硬编码)所以我认为替换代码行不能正常工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
相关资源
最近更新 更多