2014-12-02 60 views
-2

我一直要求低于这个第三方像素内插入CACHEBUSTER(随机数):填充在IMG SRC随机数

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

随机数应该在兰特URL参数来填充,但我不知道如何去做这件事。

+0

您可以更改HTML吗? – 2014-12-02 15:30:01

+0

为什么用JavaScript做到这一点?删除您对启用JavaScript的客户端的依赖关系,并在生成HTML时添加随机数(服务器端) – Bill 2014-12-02 15:43:21

回答

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被modfied后。在纯JS

// 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()); 

或生成追踪图像

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); 
+0

像魅力一样工作。对此,我真的非常感激! – 2014-12-02 16:41:33

0

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=';
<img id="pixel-img" src='http://h.nexac.com/e/a-858/s-1486/c-705/g-2423.xgi?pkey=xbue89gtzpg16&chpcm=&chpsg=&chpcr=&chpck=&rand=INSERT_CACHEBUSTER&chpth=' width='1' height='1' border='0'>

+0

有趣的事实:一旦你添加一个ID,你可以使用'document.images [“像素IMG”]' – pawel 2014-12-02 16:01:30

+0

咦,我不知道,好知道引用图像! – casraf 2014-12-02 16:02:09

0

也可以使用常规的:可以通过或者使用另一个属性避免它,例如data-src表达来代替价值。

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

+0

这个问题未标记“jQuery”。 – pawel 2014-12-02 19:04:16