createElement() 不起作用

createElement() doesn't work

本文关键字:不起作用 createElement      更新时间:2023-09-26

好吧,所以我正在尝试制作Chrome扩展程序。我在这方面有点菜鸟,这就是为什么我从教程站点中获取示例扩展并向其添加内容开始的原因。我从某个我不记得的网站上得到了它,如果你真的想要归属,我可以搜索它。法典:

var req = new XMLHttpRequest();
req.open(
"GET",
"http://api.flickr.com/services/rest/?" +
    "method=flickr.photos.search&" +
    "api_key=90485e931f687a9b9c2a66bf58a3861a&" +
    "text=hello_world&" +
    "safe_search=1&" +  
    "content_type=1&" +  
    "sort=relevance&" +  
    "per_page=24",
true);
req.onload = showPhotos;
req.send(null);
function showPhotos() {
  var photos = req.responseXML.getElementsByTagName("photo");
  for (var i = 0, photo; photo = photos[i]; i++) {
    var img = document.createElement("image");
    img.src = constructImageURL(photo);
    document.getElementById("images").appendChild(img);
  }
}
function constructImageURL(photo) {
  return "http://farm" + photo.getAttribute("farm") +
  ".static.flickr.com/" + photo.getAttribute("server") +
  "/" + photo.getAttribute("id") +
  "_" + photo.getAttribute("secret") +
  "_s.jpg";
}

所以无论如何,扩展所做的是向Flickr的API发送XMLHttpRequest,获取一些图像(XML格式的img标签)。然后,它使用 for 循环遍历这些标签,对于每个标签,它使用 createElement() 创建一个新的 img 元素,使用 constructImageURL() 函数为其提供 src 属性并将其附加到弹出页面。我想做的是让你可以实际点击这些图像,然后被带到图像的页面。我尝试基于创建图像元素的代码片段制作一段代码,但要创建锚点 (a) 元素,并将其添加到 for 循环中。它看起来像这样:

var a = document.createElement("link");
a.href = constructImageURL(photo);
a.target = "_blank";
document.getElementById("images").appendChild(a);

然后,我添加了一些代码将 img 元素附加到锚元素中,有效地制作了一个<a><img /></a>结构:

document.a.appendChild(img);

但是,它不起作用。有人可以帮忙吗?

好吧,您应该通过右键单击浏览器操作并单击"检查弹出窗口"来检查开发人员工具控制台,看看出了什么问题。

我想你可能想使用setAttribute,只是为了确保。链接的元素<a>不是<link>,图像的元素<img>不是<image>。此外,您不希望document.a.appendChild ,您希望将图像附加到当前变量。所以它应该是这样的:

function showPhotos() {
    var photos = req.responseXML.getElementsByTagName("photo");
    var a = document.createElement("a");
    a.setAttribute("href",constructImageURL(photo));
    a.setAttribute("target","_blank");
    var img = document.createElement("img");
    img.setAttribute("src",constructImageURL(photo));
    a.appendChild(img);
    document.getElementById("images").appendChild(a);
}