【问题标题】:Why are the images being nested within my option elements not being displayed?为什么不显示嵌套在我的选项元素中的图像?
【发布时间】:2021-01-22 21:47:32
【问题描述】:

奇怪的是,当我使用 div 元素作为父元素,然后在其中嵌套其他 div 时,会显示图像。当我单击检查时,我可以看到图像在那里。控制台没有通过错误,所以我真的不知道我可能哪里出错了

const url = "https://restcountries.eu/rest/v2/all";
const select = document.querySelector("select");

fetch(url)
.then(res => res.json())
.then(data => data.forEach(countryApp))

function countryApp(myData) {
  let option = document.createElement("option");
  let ctn = document.createTextNode(myData.name);
  option.appendChild(ctn);
  let img = document.createElement("img");
  img.setAttribute("src", myData.flag);
  img.setAttribute("alt", "country flag");
  img.setAttribute("width", 20);
  img.setAttribute("height", 20);
  option.appendChild(img);
  select.appendChild(option)
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Practise App</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
    <select class="" name=""></select>
    <script src="index.js" type="text/javascript"></script>
  </body>
</html>

【问题讨论】:

  • 谢谢。我就是这么想的,但我不确定

标签: javascript html image


【解决方案1】:

原因是您不能仅使用 HTML 将图像放入option。但是,您可以通过 CSS 获得结果,而不是使用 HTML 标记来实现。

添加

&lt;option style="background-image: url(path_to_the_image.format)&gt;Some Option&lt;/option&gt;

会帮助你。但是,需要对其在不同浏览器上的工作方式进行测试。

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2017-09-08
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多