追加<a> and <img/> to document.body removes href and src

时间:2018-04-06 01:28:47

标签: javascript html

So, I'm creating an article block like this:

<article>
    <figure>
        <img src="source" />
    </figure>
    <div>
        <a href="link"/>
    </div>
</article>

This is my js code:

var linkElement = document.createElement('a');
var linkText = document.createTextNode(*some text*);
linkElement.appendChild(linkText);
linkElement.href = *link*;

var imgElement = document.createElement('img');
imgElement.setAttribute("src", *some path*);
imgElement.setAttribute("width", "304");
imgElement.setAttribute("height", "228");
imgElement.setAttribute("alt", temp["name"]);

var article = document.createElement("article"),
    figure = document.createElement("figure"),
    div = document.createElement("div");

div.appendChild(linkElement);
figure.appendChild(imgElement);
article.appendChild(figure);
article.appendChild(div);

document.querySelector('article').appendChild(article);

This is my html code:

<body>

     <header></header>

     <section>
         <article></article>
     </section>

     <footer></footer>

    <script src = *src of my js*></script>

</body>

If I create one article block, everything is fine. The problem arises when I create an array of article blocks. Every block except the last one loses its href and src for the 'a' and 'img'tags. An empty image box appears and the text without the link appears. Can anyone explain why it happens and how I can change that?

Output 我打印了FB电影页面列表及其图片和页面链接。

我的原始代码:

// data has a list of FB movie pages, each containing the name of t he movie and page id
function print(data)
{
//iterates through the object passed to print movie names in console.  

var target = document.querySelector('article');
var docFrag = document.createDocumentFragment();
for (var i = 0; i < data.length; i++)
    {
        var temp = data[i];
        var linkElement = document.createElement('a');
        var linkText = document.createTextNode(temp["name"]);
        linkElement.appendChild(linkText);
        //getting the link to the movie's FB page
        getLink(function(response){linkElement.href = response;},temp["id"]);

        var imgElement = document.createElement('img');
        //getting the src of the picture of the movie's page
        getPic(function(response){imgElement.setAttribute("src", response);},temp["id"]);
        imgElement.setAttribute("width", "304");
        imgElement.setAttribute("height", "228");
        imgElement.setAttribute("alt", temp["name"]);

        var article = document.createElement("article"),
            figure = document.createElement("figure"),
            div = document.createElement("div");

        div.appendChild(linkElement);
        figure.appendChild(imgElement);
        article.appendChild(figure);
        article.appendChild(div);
        console.log(article);
        docFrag.appendChild(article);
    }
    target.appendChild(docFrag);
}

function getLink(callback,id)
{
   FB.api('/'+id+'?fields=link', function(response)
   {
       callback(response.link);
   });
}
function getPic(callback,id)
{
   FB.api('/'+id+'?fields=cover{source}', function(response)
       {
      callback(response.cover.source);
  });
}

1 个答案:

答案 0 :(得分:0)

如果只是通过OP代码,它永远不会向DOM添加任何内容。 <article>已创建,并且所有内容都附加到它,但它永远不会找到通往DOM的路径。

一旦处理完毕,您必须注意分配给图像的网址。如果您将安全内容与不安全的内容混合,它们将失败。

安全内容:

<img src='https://....>

不安全的内容:

<img src='http://....>?
顺便说一句,这个演示可以重复使用并且可以轻松扩展。简单的要求是,对于每个<article>,您必须向url[]posters[]数组添加适当的网址。此外,还简化了布局:<img>嵌套<a><a>嵌套在<fig>中,<fig>嵌套在<article>内。这种安排使整个<img>成为一个链接。

演示

在演示中评论的详细信息和参考文献位于演示

下方

&#13;
&#13;
// Array of urls to sites for lnk.href
var urls = ['https://www.starwars.com', 'https://www.marvel.com'];

// Array of urls to images for img.src
var posters = ["https://imgc.allpostersimages.com/img/print/u-g-F93H7K0.jpg?w=900&h=900&p=0", "https://imgc.allpostersimages.com/img/print/u-g-F90CQI0.jpg?w=900&h=900&p=0"];

// Reference the DOM target
var target = document.querySelector('.action');

/* Create a DocumentFragment Object to add all of your articles
|| to. The only thing you should ever append to the DOM is the
|| docFrag. It's costly to add to DOM so do it only once.
*/
var docFrag = document.createDocumentFragment();

/* One loop will:
|| - create the 4 components: article, figure, a, img
|| - get the urls from the 2 arrays and assign them to 
||   lnk.href and img.src
|| - set the additional attributes to img
|| - append components: img to a--a to fig--fig to art--art to 
||   docFrag--docFrag to target(a section attached to the DOM)
*/
/* This `for` loop will go 2 times because the .length of urls[]
|| array is 2 (note: i < urls.length)
 */
for (let i = 0; i < urls.length; i++) {
  var art = document.createElement('article');
  var fig = document.createElement('figure');
  var lnk = document.createElement('a');
  lnk.href = urls[i];
  var img = document.createElement('img');
  img.src = posters[i];
  img.width = '200';
  img.height = '300';

  lnk.appendChild(img);
  fig.appendChild(lnk);
  art.appendChild(fig);
  docFrag.appendChild(art);
}

target.appendChild(docFrag);
&#13;
<!doctype html>
<html>

<head>
  <meta charset='utf-8'>
</head>

<body>

  <header></header>
  <main>
    <section class="action"></section>
  </main>
  <footer></footer>


</body>

</html>
&#13;
&#13;
&#13;

参考

What is the DOM?

DocumentFragment