当导航回页面时,是否有任何方法来保持javascript keyup
函数的结果?
在我的图书列表页面中,我有一个搜索选项,用javascript搜索页面上可用的标题。假设我在搜索框中键入harr
,就会出现哈利波特结果。如果我单击到哈利波特页面的链接,然后再回到索引页面,关键字harr
仍然在搜索框中,但它没有明显地显示结果,而是显示整个页面。
当我回到索引页面时,如果搜索框中有任何输入,js
是否会再次使用关键字运行,以便它只显示结果,而不是显示整个页面?
下面是片段:由于片段不支持多个页面,这是码页中的一个项目,我在这里为“哈利·波特”一书创建了虚拟页面。
const searchBar = document.forms['search-books'].querySelector('input');
searchBar.addEventListener('keyup', function(e) {
const term = e.target.value.toLocaleLowerCase();
const books = document.getElementsByTagName('h5');
var notAvailable = document.getElementById('notAvailable');
var hasResults = false;
Array.from(books).forEach(function(book) {
const title = book.textContent;
if (title.toLowerCase().indexOf(term) != -1) {
book.parentElement.parentElement.style.display = 'flex';
hasResults = true;
} else {
book.parentElement.parentElement.style.display = 'none';
}
});
notAvailable.style.display = hasResults ? 'none' : 'block';
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<form id="search-books">
<input type="text" placeholder="Search a book ... ">
</form>
<div class="container">
<div class="row list-single">
<div class="col-2"><img src="https://images.gr-assets.com/books/1447303603s/2767052.jpg"/></div>
<div class="col-10">
<h5> The Hunger Games</h5>
<a href="The-Hunger-Games.html">Learn</a>
</div>
</div>
<br>
<div class="row list-single">
<div class="col-2"><img src="https://images.gr-assets.com/books/1507396732s/2.jpg"/></div>
<div class="col-10">
<h5>Harry Potter</h5>
<a href="Harry-Potter.html">Learn</a>
</div>
</div>
<div class="row list-single" id="notAvailable" style="display: none;">
<div class="col-12">
<h5>Sorry, the book has not been added yet</h5>
</div>
</div>
</div>
发布于 2018-04-22 17:10:55
如果您只是将此代码(除了当前代码之外)放到脚本的顶层。它将在页面加载后立即执行(从技术上讲,一旦脚本加载),如果输入字段中有任何文本,则该文本将立即用于筛选图书条目。
const term = searchBar.value;
if (term !== '') { // test if the input fields is not empty
const books = document.getElementsByTagName('h5');
let notAvailable = document.getElementById('notAvailable');
let hasResults = false;
Array.from(books).forEach(function(book) {
const title = book.textContent;
if (title.toLowerCase().indexOf(term) != -1) {
book.parentElement.parentElement.style.display = 'flex';
hasResults = true;
} else {
book.parentElement.parentElement.style.display = 'none';
}
});
notAvailable.style.display = hasResults ? 'none' : 'block';
}
https://stackoverflow.com/questions/49968466
复制相似问题