这是我想做的事情的一个非常简短的背景。我需要创建一个非常小的 JavaScript block ,它将提供给许多网站以嵌入到它们的主页中。然后,当访问者访问这些主页时,将自动调用一个 URL,该 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 标签)。我需要动态生成它并插入 DOM(我认为),在生成“userId”的值之后,它可以作为查询参数包含在 img src URL 中。或者也许有更好的方法?当然,我会在将其发送到第三方网站之前对其进行压缩。
最佳答案
将最后一行替换为:
document.write('<a href="http://www.SomeAnalysisSite.com/"><img src="http://www.SomeAnalysisSite.com/Log/?Id=1@userId=' + userId + '" alt=""/></a>');
并检查您是否打算在上面的行中用 & 代替 @。
关于javascript - 使用 JavaScript 在页面加载时动态创建 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34693922/