我玩弄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
的列表。
你有几件事情在你的代码去反对你在这里。
host
从未定义。你大概的意思location.host
document.links
包括所有环节,包括您添加的。另一个原因改变页面内容之前,阵列复制。appendChild()
将尝试移动<a>
,这可能会破坏页面的其余部分。你可能要复制的元素。<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());
}
}
}