JavaScript 未在 div 内创建标头

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

function search() {
  var searchbar = document.getElementById("searchbar");
  if (searchbar.value != null) {
    var searchResult = document.createElement("h2");
    searchResult.value = "Search results for " + searchbar.value;
    document.getElementById("question-render").appendChild(searchResult);
  }
}
<!DOCTYPE html>
<html>

<head>
  <title>CodeGitOverflow</title>
  <link rel='stylesheet' href='css/navbar.css' />
  <script type='text/javascript' src='js/search.js'></script>
</head>

<body>

  <!-- Div for navbar -->
  <div class="navbar">
    <!-- Div for header -->
    <div class="header">
      <h1>Welcome to CodeGitOverflow</h1>
    </div>

    <!-- Div for search -->
    <div class="searchbar">
      <form action="javascript:search()">
        <input id="searchbar" type="search">
        <input type="submit" value="Search for question">
        <p>Search for a question</p>
        <noscript>This website won't work without JavaScript enabled.</noscript>
      </form>
    </div>

    <!-- Div for links -->
    <div class="links">
      <ul>
        <li><a onclick="javascript:this.style.display = 'none';" href="#home">Home</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="askQuestion.html">Ask a question</a></li>
        <li><a href="signup.html">Signup</a></li>
      </ul>
    </div>
  </div>

  <div class="question-render" id="question-render">

    <div class="questions-header">
      <h1>Questions Asked</h1>
    </div>
    <div class="questions-render-section" id="questions-render-section">
      <p>No questions asked yet.</p>
      <p>Have a question? <a href="askQuestion.html">Ask a question</a></p>
    </div>
  </div>
</body>

</html>

在 HTML 代码中,

有一个ID为'questions-render'的div,用于将搜索结果渲染为标签

在 JavaScript 代码中,

  • 我通过其标识符获取搜索栏。
  • 我检查了搜索栏的值是否不等于null。如果不是,我创建了一个变量名为
    searchResult
    ,
  • 的“h2”
  • 我将搜索结果变量的值设置为“搜索结果”+搜索栏的值
  • 然后我将其附加到
    question-render
    div
javascript html dom
1个回答
0
投票

您应该将innerText添加到标题标签中,而不是设置其值。

searchResult.innerText = "Search results for " + searchbar.innerText;
© www.soinside.com 2019 - 2024. All rights reserved.