0
大家好,我有一個應用程序,其中腳本search.js搜索JavaScript數組,並在用戶在搜索欄中輸入單詞並按下回車鍵時顯示結果列表。我試圖在文件artists.json中切換JSON數據的數組。在搜索應用程序中使用JSON數據交換JavaScript數組?
function Artist(image, title, link) {
this.image = image;
this.title = title;
this.link = link;
}
var artists = []
artists.push(new Artist("image", "item1", "1.html"));
artists.push(new Artist("image", "item2", "2.html"));
artists.push(new Artist("image", "item3", "3.html"));
artists.push(new Artist("image", "item4", "4.html"));
artists.push(new Artist("image", "item5", "5.html"));
artists.push(new Artist("image", "item6", "6.html"));
var searchBox = document.querySelector("#search");
searchBox.focus();
function doSearch(event) {
var msg = document.querySelector("#msg");
var artistList = document.querySelector("#artist-list");
artistList.innerHTML = "";
var searchTerm = searchBox.value.trim().toLowerCase();
msg.innerHTML = "";
if (event.keyCode === 13) {
if (searchTerm === "") {
msg.innerHTML = "You didn't enter anything";
msg.classList.add("error");
} else {
var count = 0;
for (var i = 0; i < artists.length; i ++) {
if (artists[i].title.toLowerCase().search(searchTerm) !== - 1) {
artistList.innerHTML += "<li><a href='artists/" + artists[i].link + "'>" + artists[i].title + "<a/></li>";
count ++;
}
//else if()
}
msg.innerHTML = "For " + searchTerm + ". We found " + count + " results.";
msg.classList.remove("error");
}
}
}
searchBox.addEventListener("keyup", doSearch, false);
var msgTxt = document.querySelector("#msg");
var artistList = document.querySelector("#artist-list");
var searchBox = document.querySelector("#search");
msgTxt.innerHTML = "";
searchBox.value = "";
searchBox.addEventListener("keyup", doSearch, false);
我想更換藝術家陣列下面這樣我就可以通過這個來代替陣列的搜索JSON數據,我可以加載JSON數據不錯,但林與如何替換功能的陣列中掙扎。任何幫助都感激不盡。
[
{
"image":"image1",
"title":"title1",
"link":"link1"
},
{
"image":"image2",
"title":"title2",
"link":"link2"
},
{
"image":"image3",
"title":"title3",
"link":"link3"
},
{
"image":"image4",
"title":"title4",
"link":"link4"
},
{
"image":"image5",
"title":"title5",
"link":"link5"
},
]
難道你不能只把json數據放在'artists'變量中嗎? –
你應該嘗試一下AJAX https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started或http://api.jquery.com/jquery.ajax/在你嘗試了一些東西之後,你可以問一個問題。事實上,這個問題不是主題,因爲有太多不同的方法來實現這一點。 –
我不想搜索JavaScript數組,我想通過AJAX加載JSON數據並搜索。 – Reypoints