<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>百度提示关键字提取</title>
<script src="jquery-3.7.1.js" type="text/javascript"></script>
<script src="aixin.js" type="text/javascript"></script>
<style>
header {
/*background: #e6be1c;*/
margin-left: 33%;
width: 22%;
transform: scale(2);
margin-top: 1%;
}
#history {
width: 80%;
margin-left: 10%;
height: 830px;
background-color: #DAF16E7F; /* 半透明的白色 */
overflow: scroll;
margin-top: 1%;
}
body {
background-image: url("background.png");
}
::-webkit-scrollbar {
display: none;
}
</style>
</head>
<body>
<header>
<label for="value">请输入关键词:</label><input list="languageList" id="value" type="text" placeholder="按Enter查询"/>
<datalist id="languageList"></datalist>
<button id="clear">清除</button>
<button id="export">导出</button>
</header>
<section>
<div id="history">
</div>
</section>
</body>
<script>
let dataArray = [];
$().ready(function () {
$("#value").focus();
$("#export").click(function () {
exportExcel();
});
$("#clear").click(function () {
$("#value").val("");
$("#history").empty();
dataArray = [];
});
/*设置监听事件,向输入框中输入内容,当键盘按键弹起的时候,将输入的内容作为参数传入到函数info中*/
$("#value").bind("keydown", function (event) {
console.log(event.keyCode)
/*当键盘按下上下键的时候,不进行监听,否则会与keyup事件起冲突*/
if (event.keyCode === 13) {
if (dataArray.length > 1000) {
alert("数据已超过1000条,请导出或清空!")
return false;
}
let value = $("#value").val();
info(value);
setTimeout(function () {
historyToBottom();
}, 100)
}
})
/*将ajax封装到函数中*/
function info(value) {
/*百度搜索框智能提示的接口*/
let url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su";
/*需要传入的参数,cb是callback的缩写*/
let data = {
wd: value,
cb: "helloword"
}
/*因为涉及跨域,这里使用jsonp*/
$.ajax({
url: url,
data: data,
type: "GET",
dataType: "jsonp",
jsonpCallback: "helloword",
/*跨域成功的时候返回的数据*/
success: function (result) {
/*返回成功之后可以在开发者工具里的Console打印看一下*/
console.log(result);
/*将获取的数据整理后返回到页面*/
let a = result.s;
let list = "";
for (let i in a) {
let l = a[i];
list += "<option>" + l + "</option>";
if (!dataArray.includes(l)) {
$("#history").append($(`<p>${l}<p/>`));
dataArray.push(l);
}
}
$("#languageList").html(list);
},
/*跨域失败的时候返回的数据*/
error: function () {
console.log("error");
alert("您的浏览器不支持,请使用chrome")
}
})
}
function exportExcel() {
let csv = dataArray.join('\n');
let link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
link.download = 'data.csv';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function historyToBottom() {
let div = $("#history");
let divHeight = div.height();
let scrollHeight = div[0].scrollHeight
div.scrollTop(scrollHeight + divHeight);
// let element = document.getElementById("history");
// element.scrollTop = scrollHeight + divHeight;
}
});
</script>
</html>