在此函數中,users
數組中的數據通過輸入的值搜索到mySearch
。包含搜索詞的行輸出到return
。將字符串化的JSON數據輸出到單獨的div中
DATA:
var users = [{"username":"nlee6p","gender":"Female","sexuality":"Down-sized asymmetric time-frame","language":"Macedonian"},
{"username":"bbrooks6q","gender":"Male","sexuality":"Multi-channelled mobile customer loyalty","language":"Luxembourgish"},{"username":"astephens6r","email":"[email protected]","gender":"Female","language":"Estonian"}]
function myFunction(e) {
if((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton'){
e.preventDefault();
var searchValue = document.getElementById("mySearch").value;
for(var i = 0; i < users.length; i++){
if((users[i]['last_name'] === searchValue) || (users[i]['username'] === searchValue) || (users[i]['first_name'] === searchValue)){
document.getElementById("return").innerHTML = JSON.stringify(users[i]);
return;
}
}
}
}
HTML
<input type="search" id="mySearch" onkeypress="myFunction(event)"/>
<button id="searchButton" onClick="myFunction(event)">SEARCH</button>
<div id="return">
<div id="usernameOut">
</div>
<div id="firstNameOut">
</div>
</div><!--return-->
我的問題
是否有可能在輸出個別的div將字符串數據沒有jQuery? 當前輸出是與搜索詞相關的整行數組。我正在尋找一種方法來分割排列,並在各自的div標籤中顯示各個組件(如果更容易,則在表格中顯示)
例如,當輸出字符串時,將顯示username
值在usernameOut
,first-name
在firstNameOut
等
我用過去Jput,但這是針對要在本地顯示通過一個C#應用程序,在C#編譯jQuery是一個有點噩夢的頁面。
使用香草JS的答案表示讚賞,但如果唯一的方法是通過jQuery,那麼我不會太困擾。
JsFiddle (that doesn't work for some reason)
(很抱歉,如果這個不清楚,我會進行必要的修改)
是的,這是可能的。只是不要將數據串聯起來,只是遍歷所有這些div,添加對象的值(users [i])。用戶名)而不是將字符串化版本放入一個div。線索是youra rray包含可以訪問的對象,它是JSON.stringify將它變成一個字符串,所以你根本不需要拆分字符串。哪部分不工作?代碼中沒有任何jquery,那麼爲什麼你需要它? – Shilly
@Shilly謝謝你的幫助!我正在尋找解決方案,幾乎所有的人都是jQuery,我需要一些適合我現有代碼的東西。我也試圖解決'.stringify'這意味着解析已經解析的東西....我想我現在有它。即'document.getElementById(「usernameOut」)。innerHTML =(users [i] .username);' – gezer4000