如何动态建立一个列表,在JavaScript和HTML中显示

问题描述 投票:0回答:1

我玩弄Web开发和寻找测试一些动态生成的内容,特别是刚刚在Chrome扩展弹出,列出所有网站页面上的链接。我引用一个很好的资源here但我有output标签与一个ul和该列表,以显示在页面上创建li的测试。

popup.html

<div>
  <h3>Page output</h3>
  <output id="outputkey3">pages go here</output>
</div>

popup.js

function (tabs) {
  var tab = tabs[0];
  var url = tab.url;
  if (url != null) {
      var host = new URL(url).hostname;
    ...

var outputKey3 = document.getElementById("outputKey3")
if (outputKey3 != null) {
  for(var i = document.links.length; i --> 0;) {
    if(document.links[i].hostname === host) {
      //urls.push(document.links[i].href);
      outputKey3.appendChild(document.links[i]);
    }
  }
}

即使是单链路上,这似乎并不奏效。不知道这是为了与列表与不与前一个号码或•格式化数据的另一个元素来完成。我真正想要做的是只显示,看起来像数据的每个索引值的新线,也许一堆p的列表。

javascript html html5 google-chrome-extension appendchild
1个回答
0
投票

你有几件事情在你的代码去反对你在这里。

  1. host从未定义。你大概的意思location.host
  2. 你很少需要一台主机比较主机名。一个包括港口和一个没有。
  3. 作为最佳实践,你要使用数组的形式克隆。这是因为列表可以改变,而你正在计算。
  4. document.links包括所有环节,包括您添加的。另一个原因改变页面内容之前,阵列复制。
  5. appendChild()将尝试移动<a>,这可能会破坏页面的其余部分。你可能要复制的元素。
  6. <output>可具有被抑制的添加语义。其目的是为计算结果,并可能只有phrasing content。考虑更换为一个<div>如果你不想<ul>

使用克隆建议

var outputKey3 = document.getElementById("outputKey3")
if (outputKey3 != null) {
  // Get new array of filtered links
  // Document.links is not an array, but can be used by Array.prototype
  let links = Array.prototype.filter.call(document.links, function(link) {
    return (link.hostname === location.hostname)
      && (link.parentElement !== outputKey3);
  });
  // For each link, change its value to a clone of it
  let newLinks = link.map(function(link) {
    return link.cloneNode();
  });
  // For each clone, add it to the list.
  newLinks.forEach(function(link) {
    outputKey3.appendChild(link);
  });
}

如果你必须使用一个for循环:

var outputKey3 = document.getElementById("outputKey3")
if (outputKey3 != null) {
  for(var i = document.links.length; i-- > 0;) {
    if((document.links[i].hostname === location.hostname)
    && (link.parentElement !== outputKey3)) {
      //urls.push(document.links[i].href);
      outputKey3.appendChild(document.links[i].cloneNode());
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.