[英]Using JavaScript to dynamically create HTML on page load
Here is a very brief background of what I want to do. 这是我要做什么的非常简短的背景。 I need to create a very small block of JavaScript that will be given to many websites to embed in their home pages.
我需要创建一个非常小的JavaScript块,将其分配给许多网站以嵌入其主页中。 Then, when visitors hit those home pages, a URL will automatically get called that collects certain statistics and returns a small image.
然后,当访问者访问这些主页时,将自动调用一个URL,该URL收集某些统计信息并返回一个小图像。 I have some of this in place already as follows:
我已经将这些设置如下:
<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>
The piece I don't know how to do is the very last line (with the img tag). 我不知道该怎么做的是最后一行(带有img标签)。 I need to generate this dynamically and inserted into the DOM (I think), after the value of "userId" is generated so it can be included as a query parameter in the img src URL.
在生成“ userId”的值之后,我需要动态生成此代码并将其插入DOM(我认为),以便可以将其作为查询参数包含在img src URL中。 Or perhaps there is a better way?
还是有更好的方法? Of course, I'll minify this before it's sent to third party websites.
当然,在将其发送到第三方网站之前,我将对其进行最小化。
Replace last line with: 将最后一行替换为:
document.write('<a href="http://www.SomeAnalysisSite.com/"><img src="http://www.SomeAnalysisSite.com/Log/?Id=1@userId=' + userId + '" alt=""/></a>');
And check if you mean to put & in place of @ in the above line. 并检查您是否要在以上行中用&代替@。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.