【问题标题】:Change IMG SRC based on referrer URL using javascript使用 javascript 基于引用 URL 更改 IMG SRC
【发布时间】:2020-10-12 17:48:39
【问题描述】:

我在这方面不是最好的,但我想知道是否有一种方法可以使用 javascript 基于引用 URL 更改图像 src。我已经把它拼凑在一起,但它不起作用,我不知道为什么。谢谢

<script>
  var ref = document.refferer;
   if(ref.includes("dev.mastercoolproducts.com")){
     $(document).ready(function() {
  $("#fc-logo").attr("src","https://essickair.foxycart.com/cache?url=https://www.dropboxusercontent.com/s/uhy2eoxjojeqwsj/mc-logo.png?dl=0");
       });
   }else{
     $(document).ready(function() {
    $("#fc-logo").attr("src","https://essickair.foxycart.com/cache?url=https://dl.dropboxusercontent.com/s/q635dlso4f8pdol/ac-color.png?dl=0");
       });
     }
</script>

【问题讨论】:

  • “但它不工作,我不知道为什么” - 然后开始调试它。添加console.log()s 并检查值或使用调试器并单步执行您的代码。
  • document.referrer 不是document.refferer
  • @Andreas 我正在浏览控制台,但无法辨别问题所在。它标记了一个错误,说我没有我确实有的开放括号,所以我对这个问题感到迷茫。但是谢谢,我会牢记这一点

标签: javascript jquery image src referrer


【解决方案1】:

您似乎可能在文档初始化之前运行了此代码。您只想运行代码来检查您的文档是否已初始化一次。我已经修改了您的代码,并认为这应该可以解决它:

//Only run once the document is ready
$(document).ready(function() {
  // this sets the value to '' if refferrer is somehow empty
  var ref = document.refferer || '';
  // since you'll be searching for this node multiple times, just store it in a variable:
  var logoImg = $("#fc-logo");
  if (ref.includes("dev.mastercoolproducts.com")) {
    logoImg.attr("src", "https://essickair.foxycart.com/cache?url=https://www.dropboxusercontent.com/s/uhy2eoxjojeqwsj/mc-logo.png?dl=0");
  } else {
    logoImg.attr("src", "https://essickair.foxycart.com/cache?url=https://dl.dropboxusercontent.com/s/q635dlso4f8pdol/ac-color.png?dl=0");
  }
})

【讨论】:

  • 老兄这修复了它。非常感谢!
猜你喜欢
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多