【问题标题】:Where did the text of the h1 disappear to?h1 的文字消失到哪里去了?
【发布时间】:2023-01-10 21:21:56
【问题描述】:

我使用 API 在 JS 中创建了 h1,但现在它没有出现在我的网页上。 如果我尝试更改样式,它周围的东西会发生变化,但文本仍然不会出现。

这是我的 HTML:

<div id="profile-image" class="profile-image"></div>
<div class="profile-name"></div>

这是我的 JS:

fetch(GITHUB_URL) 
.then(function(response) {
 return response.json();
 })
.then(function (data) {
 const img = document.createElement('img'); 
 img.src = data.avatar_url;
 img.alt = 'Github prof'
 document.querySelector(".profile-image").appendChild(img); 

 const h1 = document.createElement('h1');
 h1.src = data.name;
 h1.alt = "my name";
 document.querySelector(".profile-name").appendChild(h1);

该图像有效并且在我的网页上可见。 h1 应该出现在它下面,但事实并非如此。当我使用 console.log(data.name) 时,会出现我想要的文本。我的控制台没有错误。只是 h1 的文本不会出现。 谢谢

【问题讨论】:

  • HTML 标头没有 src 或 alt 属性
  • 正如上面提到的,h1 中没有 src 属性。您可以使用 innerTEXTinnerHTML 更改 h1 的文本

标签: javascript html dom


【解决方案1】:

HTML heading element 没有 srcalt 属性。

也许你的意思是

const data = {"name": "Fred", "avatar_url": "https://via.placeholder.com/150" }
const img = new Image();
img.src = data.name;
img.alt = 'Github prof';
document.querySelector(".profile-image").appendChild(img);
const h1 = document.createElement('h1');
h1.appendChild(document.createTextNode(data.name));
document.querySelector(".profile-name").appendChild(h1);
<div id="profile-image" class="profile-image"></div>
<div class="profile-name"></div>

【讨论】:

    【解决方案2】:

    h1 标签没有 src 属性,如果你想在 h1 中显示值,请使用 innerText 而不是 src

    利用

    const h1 = document.createElement('h1');
     h1.innerText = "sample text";
     h1.alt = "my name";
     document.querySelector(".profile-name").appendChild(h1);
    &lt;div class="profile-name"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      相关资源
      最近更新 更多