我正在从事 freecodecamp 的维基百科查看器项目。我有一个可行的示例,但有一些事情我不知道该怎么做。
首先,如何通过在输入字段中键入内容并按 Enter 或单击按钮来执行某些 AJAX 请求?
接下来,当我尝试在输入字段中键入内容并按 Enter 键时,结果将显示在网页中。但是,当我尝试再次输入并输入时,新结果不会显示,但以前的结果消失,我必须再次输入并按 Enter 才能获得新结果。
我知道还有其他使用 jQuery 的帖子,但我也不理解并且不想在纯 JavaScript 中使用 jQuery。
var url = 'https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=10&origin=*&search=';
var inputSearch = document.myForm.search;
var searchBtn = document.myForm.searchBtn;
var list = document.getElementById("list");
var random = document.getElementsByClassName('random')[0];
random.addEventListener("click" , function(){
window.open("https://en.wikipedia.org/wiki/Special:Random");
});
function requestData ( e ) {
var inputStr = e.target.value;
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if ( request.readyState === 4 ) {
if ( request.status === 200 ) {
var dataObj = JSON.parse(request.responseText);
var titles = dataObj[1];
var descriptions = dataObj[2];
var links = dataObj[3];
document.myForm.innerHTML += "<h2><span>" + links.length + "</span> results for \"" + "<span>" + inputStr + "</span>" +"\" </h2>";
list.innerHTML = "";
for ( var i = 0; i < titles.length; i++ ) {
var li = "<li><a target='_blank' href=" + links[i] + ">" + titles[i] + "</a></li>";
list.innerHTML += li;
}
}
else {
console.log("Server responded with following error code : " + request.status);
}
}
};
if ( e.keyCode === 13 ) {
console.log(e.type);
request.open("GET" , url + inputStr);
request.send(null);
e.preventDefault();
}
}
inputSearch.addEventListener("keydown" , requestData);
searchBtn.addEventListener("click" , requestData);
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* CSS reset ends here */
body {
font-size: 16px;
font-family: 'Oxygen', sans-serif;
}
.container-wrapper {
margin: 0 auto;
text-align: center;
height: 100vh;
}
header {
/*background-color: #fc3e5b;*/
padding: 80px 0;
}
header h1 {
font-family: 'Anton', sans-serif;
font-size: 70px;
padding: 30px 0 80px 0;
color: #fc3e5b;
}
form input , form button {
padding: 10px 8px;
font-size: 22px;
border: 1px solid #fc3e5b;
outline: 0;
display: inline;
margin: 0;
}
form button {
background-color: #fc3e5b;
color: #fff;
}
h2 {
font-size: 25px;
margin-top: 32px;
}
h2 span {
font-weight:bold;
color: #fc3e5b;
}
.random {
padding: 22px 7px;
border-radius: 100%;
margin: 20px 0 15px 0;
}
.random:hover {
border: 5px solid #fc3e6b;
}
#list {
width: 75%;
margin: 0 auto;
}
#list li {
padding: 16px 8px;
background-color: #fc3e5b;
margin: 12px 0;
text-align: left;
font-size: 22px;
}
#list li a {
text-decoration: none;
color: #fff;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title> Wikipedia Viewer </title>
<link href="https://fonts.googleapis.com/css?family=Anton|Oxygen" rel="stylesheet">
<link rel="stylesheet" href="wikipedia.css">
</head>
<body>
<div class="container-wrapper">
<header>
<h1> Wikipedia Viewer </h1>
<form action="" name="myForm">
<input type="text" name="search" /><button name="searchBtn">Search</button>
<br>
<button name="btnRandom" class="random"> Random<br>Article </button>
</form>
</header>
<div class="container">
<ul id="list"></ul>
</div>
</div>
<script src="wikipedia.js"></script>
</body>
</html>
最佳答案
我已经更新了您的代码,请参阅此 fiddle 以获取工作代码 Ajax call on click of button
检查它是否按照您的需要工作。
以下是我对您的代码所做的更改列表:-
- 我已将“keydown”事件更改为“keyup”事件,因为 “keydown”我们没有收到按下的键的值。
- 我已经分离了搜索按钮点击事件的函数调用 并输入按键事件以使其更清晰。
- 我已为搜索输入框提供了 id,以在“requestData()”函数调用中获取其值。
- 如果我们在表单中有(而不是输入类型=“按钮”),则单击按钮表单就会被提交。
- 我已将“event.preventDefault()”添加为“requestData()”中的第一行,因为按下 Enter 按钮后表单会自动提交。
- 添加了一个段落来显示结果统计信息
- 将此行
document.myForm.innerHTML +=
更改为document.getElementById("results_stats").innerHTML
希望这对您有帮助。
HTML:-
<div class="container-wrapper">
<header>
<h1> Wikipedia Viewer </h1>
<form action="" name="myForm">
<input type="text" name="search" id="txt_search" /><input type="button" name="searchBtn" value="Search"/>
<br>
<input type="button" name="btnRandom" class="random" value="Random Article"/>
<p id="results_stats"></p>
</form>
</header>
<div class="container">
<ul id="list"></ul>
</div>
JAVASCRIPT:-
var url = 'https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=10&origin=*&search=';
var inputSearch = document.myForm.search;
var searchBtn = document.myForm.searchBtn;
var list = document.getElementById("list");
var random = document.getElementsByClassName('random')[0];
random.addEventListener("click" , function(){
window.open("https://en.wikipedia.org/wiki/Special:Random");
});
function getDataFromInputBox(e){
console.log("Value Entered"+inputStr);
if ( e.keyCode === 13 ) {
requestData(e);
}
}
function requestData(e) {
e.preventDefault();
console.log(e.target);
var inputStr = document.getElementById("txt_search").value;
if(inputStr != ""){
console.log(inputStr);
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if ( request.readyState === 4 ) {
if ( request.status === 200 ) {
var dataObj = JSON.parse(request.responseText);
var titles = dataObj[1];
var descriptions = dataObj[2];
var links = dataObj[3];
document.getElementById("results_stats").innerHTML = "<h2><span>" + links.length + "</span> results for \"" + "<span>" + inputStr + "</span>" +"\" </h2>";
list.innerHTML = "";
for ( var i = 0; i < titles.length; i++ ) {
var li = "<li><a target='_blank' href=" + links[i] + ">" + titles[i] + "</a></li>";
list.innerHTML += li;
}
}
else {
console.log("Server responded with following error code : " + request.status);
}
}
};
request.open("GET" , url + inputStr);
request.send(null);
//e.preventDefault();
}
else{
document.getElementById("results_stats").innerHTML;
list.innerHTML = "";
alert("Enter a value");
}
}
inputSearch.addEventListener("keyup" , getDataFromInputBox);
searchBtn.addEventListener("click" , requestData);
document.myForm.addEventListener("submit",requestData);
CSS:-
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* CSS reset ends here */
body {
font-size: 16px;
font-family: 'Oxygen', sans-serif;
}
.container-wrapper {
margin: 0 auto;
text-align: center;
height: 100vh;
}
header {
/*background-color: #fc3e5b;*/
padding: 80px 0;
}
header h1 {
font-family: 'Anton', sans-serif;
font-size: 70px;
padding: 30px 0 80px 0;
color: #fc3e5b;
}
form input , form button {
padding: 10px 8px;
font-size: 22px;
border: 1px solid #fc3e5b;
outline: 0;
display: inline;
margin: 0;
}
form button {
background-color: #fc3e5b;
color: #fff;
}
h2 {
font-size: 25px;
margin-top: 32px;
}
h2 span {
font-weight:bold;
color: #fc3e5b;
}
.random {
padding: 22px 7px;
border-radius: 100%;
margin: 20px 0 15px 0;
}
.random:hover {
border: 5px solid #fc3e6b;
}
#list {
width: 75%;
margin: 0 auto;
}
#list li {
padding: 16px 8px;
background-color: #fc3e5b;
margin: 12px 0;
text-align: left;
font-size: 22px;
}
#list li a {
text-decoration: none;
color: #fff;
}
关于javascript - 如何将 click 和 keydown 绑定(bind)到 Vanilla JavaScript 中的输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44224075/