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 代码中,
searchResult
,question-render
div您应该将innerText添加到标题标签中,而不是设置其值。
searchResult.innerText = "Search results for " + searchbar.innerText;