使用JavaScript在页面加载时动态创建HTML

时间:2016-01-09 13:17:37

标签: javascript html5

这是我想要做的非常简短的背景。我需要创建一个非常小的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中。或许还有更好的方法?当然,我会在发送到第三方网站之前将其缩小。

2 个答案:

答案 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)

  1. 生成userId;
  2. 使用新的userId;
  3. 创建网址
  4. 创建一个新的img元素:document.createElement('img');
  5. 插入新的src属性img.setAttribute('src',imgUrl);
  6. 创建一个新元素:document.createElement('a');
  7. 插入新的href属性link.setAttribute('href',linkUrl);
  8. 在“a”link.appendChild(img);
  9. 中插入“img”
  10. 将“a”元素插入“somediv”元素内的dom
  11. 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>