【问题标题】:Populate random number in a img src在 img src 中填充随机数
【发布时间】:2014-12-02 15:23:35
【问题描述】:

我被要求在下面的这个第三方像素中插入一个 CACHEBUSTER(随机数):

<img src='http://yourdomain.com?dfew&chpcm=&chpsg=&chpcr=&chpck=&rand=INSERT_CACHEBUSTER&chpth=' width='1' height='1' border='0'>

随机数应该填充到 rand URL 参数中,但我不知道该怎么做。

【问题讨论】:

  • 你能改变那个 HTML 吗?
  • 为什么要用 JavaScript 做这个?删除对启用 JavaScript 的客户端的依赖,并在生成 HTML 时添加随机数(服务器端)

标签: javascript html image pixel tagging


【解决方案1】:

您可以将“INSERT_CACHEBUSTER”替换为时间戳,如下所示:

var img = document.querySelector('img[src*="INSERT_CACHEBUSTER"]')
img.src = img.src.replace('INSERT_CACHEBUSTER', (new Date()).getTime())

时间戳比随机数更有效,因为它每毫秒递增一次,因此它几乎无法重复随机数的情况,但如果你真的想要随机:

img.src = img.src.replace('INSERT_CACHEBUSTER', Math.random())

编辑:两种解决方案都可以两次访问跟踪服务器:一次使用占位符字符串,然后在修改 src 后再次访问。您可以通过使用另一个属性来避免它,例如data-src:

// HTML
<img data-src='http://blahblah&rand=INSERT_CACHEBUSTER' width='1' height='1' border='0'>

// JS
var img = document.querySelector('img[data-src*="INSERT_CACHEBUSTER"]')
img.src = img.getAttribute('data-src').replace('INSERT_CACHEBUSTER', (new Date()).getTime());

或者用纯JS生成跟踪图

var img = new Image();
img.width = 1;
img.height = 1;
img.src = 'http://h.nexac.com/e/a-858/s-1486/c-705/g-2423.xgi?pkey=xbue89gtzpg16&chpcm=&chpsg=&chpcr=&chpck=&rand=' + (new Date()).getTime() +'&chpth=';
document.body.appendChild(img);

【讨论】:

  • 工作就像一个魅力。我真的很感激!
【解决方案2】:

var image = document.querySelector('#pixel-img');
image.src = 'http://h.nexac.com/e/a-858/s-1486/c-705/g-2423.xgi?pkey=xbue89gtzpg16&chpcm=&chpsg=&chpcr=&chpck=&rand=' + Math.round(Math.random(99999) * 100000) + '&chpth=';
&lt;img id="pixel-img" src='http://h.nexac.com/e/a-858/s-1486/c-705/g-2423.xgi?pkey=xbue89gtzpg16&amp;chpcm=&amp;chpsg=&amp;chpcr=&amp;chpck=&amp;rand=INSERT_CACHEBUSTER&amp;chpth=' width='1' height='1' border='0'&gt;

【讨论】:

  • 有趣的事实:添加 ID 后,您可以使用 document.images['pixel-img'] 引用图像
【解决方案3】:

您也可以使用正则表达式来替换该值。

var src = $("img").prop( "src" );
src = src.replace( /(.+)(rand=)(.+)(&)(.+)/, "$1rand="+rndVal+"&$5");
$("img").prop( "src", src );

当您使用正则表达式时,( ) 之间的每个单词都可以使用 $i 访问,其中 i 是第 i 个位置。

http://codepen.io/anon/pen/MYarjN

【讨论】:

  • 该问题未标记jQuery
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 2017-06-04
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
相关资源
最近更新 更多