我想尝试使用与YouTube和其他网站中的搜索标签类似的输入标签中的自动完成选项。我正在使用YouTube-API来显示带有搜索输入的最近视频的列表。
使用YouTube-API创建了一个网页,以显示与用户输入相对应的最新视频。
HTML CODE
<body class="bg-warning">
<div class="container-fluid py-4 main">
<h1 class="titlename text-center pb-4"><img src="img/580b57fcd9996e24bc43c545.png" height="50" class="mr-2 mb-1" alt="mdb logo">Youtube APP</h1>
<div class="container rounded text-center bg-success mb-4">
<div class="container input-group py-4">
<input type="text" id="youtube_search" placeholder="Search" class="form-control">
<div class="input-group-append">
<button type="button" class="btn btn-primary" id="search"><i class="fa fa-search" aria-hidden="true"></i></button>
</div>
</div>
</div>
<div class="container" id="videoDisplay">
<!-- video search result -->
</div>
</div>
JAVASCRIPT CODE
let keyWordsearch = () => {
gapi.client.setApiKey('API_KEY');
gapi.client.load('youtube', 'v3', () => {
makeRequest();
});
}
let makeRequest = () => {
let q = document.getElementById('youtube_search').value;
let request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute((response) => {
document.getElementById('videoDisplay').innerHTML = '';
let srchItems = response.result.items;
$.each(srchItems, function(index, item) {
let vidTitle = item.snippet.title;
let vidDescription = item.snippet.description;
let vidID = item.id.videoId;
let channel = item.snippet.channelTitle
document.getElementById('videoDisplay').innerHTML += `<div class="border rounded border-dark p-3 mb-2 bg-white"><h1 class="text-center title">${vidTitle}</h1><h3>Owned By : ${channel}</h3></h3><p>${vidDescription}</p><div class="embed-responsive embed-responsive-21by9 rounded"><iframe class="embed-responsive-item" src="https://www.youtube.com/embed/${vidID}"></iframe></div></div>`;
});
});
}
//user clicked on the add button
//if there is any text inside the task field, add the text to the todo list
document.getElementById('search').addEventListener('click', keyWordsearch);
//user pressed enter
//if there is any text inside the task field, add the text to the todo list
document.getElementById('youtube_search').addEventListener('keydown', (event) => {
if (event.keyCode == 13) {
keyWordsearch();
}
});
请使用您的API密钥
能够实现自动完成选项。 代码链接为https://github.com/Shefali-Upadhyay/Youtube-App