在分配中,我們應該使用搜索按鈕上的事件偵聽器來構建一個簡單的搜索功能。所以有一個名爲store.js的文件,它有一個全局數組對象來模擬相冊數據庫。用戶搜索藝術家時,應在新頁面上顯示結果。我得到它遍歷數組,獲得結果,並顯示在頁面上。 我弄不明白的是如何打開「搜索結果」頁面,並在那裏顯示結果。如果我將結果保存到全局變量並嘗試將其顯示在新頁面上,它會顯示「未定義」。 只需要注意,這是一個初學者客戶端JS類,所以不應該有任何需要的「後端」語言。 我會很感激任何提示或批評。JavaScript簡單搜索 - 如何在新頁面上顯示結果?
這是從分配的指令:
- 創建一個名爲search.js文件。
- 在search.js腳本中創建一個由名爲search的函數處理的事件偵聽器,該函數處理搜索的 提交按鈕的onclick事件。
- 當我輸入一個藝術家的名字(我現在只打算按照藝術家的名字搜索),在搜索框中點擊提交,你的搜索 函數應該循環遍歷 store.js中相冊的假數據庫文件。打開一個新頁面,並在 該頁面的列表中顯示結果。你將需要使用dom操作這部分。
謝謝!
HTML:
<button id="searchButton">Search</button>
<div id="displayResult"></div>
JS:
//Search
var result = "Nothing found!";
function displaySearch() {
"use strict";
var displayResult = document.getElementById("displayResult");
window.open("search.html") //How do I display the result in this page?
displayResult.style.display = "block";
displayResult.innerHTML = result;
}
function doSearch() {
"use strict";
var searchField = document.getElementById("searchField").value;
for (var i = 0; i < db.length; i++) {
if (db[i].artist.toUpperCase() === searchField.toUpperCase()) {
result = db[i].artist;
}
}
displaySearch();
}
function search() {
"use strict";
var searchButton = document.getElementById("searchButton");
searchButton.addEventListener("click", doSearch, false);
}
window.addEventListener("load", search, false);
FAKE DB:
var db = []; //array of fake album database
function Album(id, title, artist, price, relDate, qty, tracks) {
"use strict";
this.id = id;
this.title = title;
this.artist = artist;
this.price = price;
this.relDate = relDate;
this.qty = qty;
this.tracks = tracks;
db.push(this);
}
var album1 = new Album("01", "Animals", "Pink Floyd", 18.99, "01/23/1977", 1000, ["1. Pigs on the Wing 1", "2. Dogs", "3. Pigs (Three Different Ones)", "4. Sheep", "5. Pigs on the Wing 2"]);
var album2 = new Album("02", "Cosmic Slop", "Funkadelic", 19.99, "07/09/1973", 500, ["1. Nappy Dugout", "2. You Can’t Miss What You Can’t Measure", "3. March to the Witch’s Castle", "4. Let’s Make It Last", "5. Cosmic Slop", "6. No Compute", "7. This Broken Heart", "8. Trash A-Go-Go", "9. Can’t Stand the Strain"]);
var album3 = new Album("03", "Ghost Reveries", "Opeth", 14.99, "08/29/2005", 1500, ["1. Ghost of Perdition", "2. The Baying of the Hounds", "3. Beneath the Mire", "4. Atonement", "5. Reverie/Harlequin Forest", "6. Hours of Wealth", "7. The Grand Conjuration", "8. Isolation Years"]);
這是一個學校任務,你希望我們爲你解決嗎?那麼你會學到什麼? :) – CharlieBrown
我已經提交了作業。我不想讓它解決,我想學習如何去做。我要求提示,而不是解決方案! 「我會很感激任何提示或批評。」 我爲什麼要複製/粘貼確切的作業指示和我的真實姓名?我的教授不傻。 – cabricz
好吧,我在開玩笑。你需要的是訪問打開窗口的「文檔」並在那裏操作。我不知道'search.html'具有什麼,您可以修改該DOM內容或創建一個空白頁面並在其中創建結果。 :) – CharlieBrown