这是我想要做的非常简短的背景。我需要创建一个非常小的JavaScript块,它将被提供给许多网站以嵌入他们的主页。然后,当访问者访问这些主页时,将自动调用URL以收集某些统计信息并返回一个小图像。我已将其中的一些内容如下:
<script>
/* Determine if there is a cookie already exists and get its value if not. */
var userId;
match = document.cookie.match(new RegExp("someUserId" + '=([^;]+)'));
if (match)
userId = match[1];
else {
/* generate a random 10 character string */
userId = (Math.random() + 1).toString(36).substring(5, 15);
/* Store this as a cookie value */
<needs to be done>
}
/* This is what I need help with. A page is called when the home page loads to collect some stats and return a small image */
<a href="http://www.SomeAnalysisSite.com/"><img src="http://www.SomeAnalysisSite.com/Log/?Id=1@userId=xxx" alt=""/></a>
</script>
我不知道该怎么做的是最后一行(带有img标签)。在生成“userId”的值之后,我需要动态生成并插入DOM(我认为),因此可以将其作为查询参数包含在img src URL中。或许还有更好的方法?当然,我会在发送到第三方网站之前将其缩小。
答案 0 :(得分:2)
将最后一行替换为:
document.write('<a href="http://www.SomeAnalysisSite.com/"><img src="http://www.SomeAnalysisSite.com/Log/?Id=1@userId=' + userId + '" alt=""/></a>');
并检查你是否愿意放&amp;代替@在上面一行。
答案 1 :(得分:0)
var userId;
/*1*/
userId = (Math.random() + 1).toString(36).substring(5, 15);
var siteUrl = "http://www.SomeAnalysisSite.com/"
/*2*/
var imgUrl = siteUrl + "Log/?Id=1@userId=" + userId;
var linkUrl = siteUrl;
/*3*/
var img = document.createElement('img');
/*4*/
img.setAttribute('src', imgUrl);
/*5*/
var link = document.createElement('a');
/*6*/
link.setAttribute('href', linkUrl);
/*7*/
link.appendChild(img);
/*8*/
document.getElementById("somediv").appendChild(link);
<html>
<body>
<div id="somediv">
</body>
<script>
</script>
</html>