@xunuo
2018-08-13T15:49:33.000000Z
字数 2356
阅读 960
前端
功能: 我可以在一个搜索框搜索维基百科的条目,并看到输出结果。
功能: 我可以点击一个按钮就看到一个随机的维基百科条目。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<title></title>
<style>
body {
background-color: #092B40;
}
h1 {
text-align: center;
color: #FFFFFF;
}
a {
margin-left: 43%;
text-align: center;
}
.input-group-design {
margin: 50px 30%;
font-size: 16px;
}
#result ul {
list-style: none;
padding: 0;
}
#result li {
color: black;
font-weight: 300px;
padding-left: 6px;
}
#result li a {
padding: 16px 16px 2px 24px;
margin: 20px 200px;
font-weight: bold;
display: block;
background-color: #E6E6E6;
}
</style>
</head>
<body>
<h1>Wikipedia Entrance</h1>
<a href="http://en.wikipedia.org/wiki/Special:Random">Click Here For A Random Wikipedia Page</a>
<div class="input-group-design">
<div class="input-group">
<input id="input-text" type="text" class="form-control">
<span class="input-group-btn">
<button id="search-btn" class="btn btn-default">GO</button>
</span>
</div>
</div>
<div>
<selection id="result">
</selection>
</div>
<script type="text/javascript">
var paraJack = {
wikiItemBaseUrl: 'https://en.wikipedia.org/wiki/',
resultNum: 12 /*总共展示12条数据*/
}
$('#search-btn').click(function() { /*点击GO按钮时*/
var searchStr = document.getElementById('input-text').value; /*取输入框中的值*/
console.log(searchStr);
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&titles=' +
encodeURIComponent(searchStr) + '&action=query&format=json&list=search&srsearch=' +
encodeURIComponent(searchStr) + '&srlimit=' + paraJack.resultNum + '&srprop=snippet&callback=?',
function(data) {
genResultDom(paraJack.resultNum);
var $anchors = $('#result a');
$.each(data.query.search, function(index, val) {
var $theAnchor = $anchors.eq(index),
$p = $theAnchor.find('p'),
$h3 = $theAnchor.find('h3'),
title = val.title, //结果项标题
snippet = val.snippet; //结果项内容提要
$h3.html(title);
$p.html(snippet);
$theAnchor.attr({
href: paraJack.wikiItemBaseUrl + title
//用结果项标题生成URL
});
});
$('#result').show(); //显示结果
});
});
function genResultDom(resultNum) {
if(typeof resultNum === 'number') {
var $result = $('#result'),
$ul = $result.html('<ul></ul>').find('ul');
for(var i = 0; i < resultNum; i++) {
$ul.append($('<li><a href="" target="_blank"><h3></h3><p></p></a></li>'));
}
}
}
</script>
</body>
</html>