我正在尝试使用Youtube Data API v3进行基本搜索操作。当我点击任何按钮时,字符串被传递给searchyoutube
函数。我希望此字符串成为搜索查询。
这是名为app.js的JS:
"use strict";
var query;
function searchyoutube (query){
var request = gapi.client.youtube.search.list({
part: 'snippet',
type: 'video',
q: query
});
console.log(query);
request.execute(function(response){
console.log("Whatever");
});
}
function init()
{
gapi.client.setApiKey("API KEY");
gapi.client.load("youtube","v3",function(){
//api ready
});
}
这是HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="yy.css">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300,100' rel='stylesheet' type='text/css'>
<title>Title</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=init"></script>
</head>
<body>
<h3>Header</h3>
<h5>Random Header</h5>
<form method="post">
<ul class="youtube-categories" id="youtube-category">
<li><button onClick ="searchyoutube('music')">Music</li>
<li><button onClick ="searchyoutube('sports')">Sports</li>
<li><button onClick ="searchyoutube('gaming')">Gaming</li>
<li><button onClick ="searchyoutube('movies')">Movies</li>
<li><button onClick ="searchyoutube('tv shows')">TV Shows</li>
<li><button onClick ="searchyoutube('news')">News</li>
<li><button onClick ="searchyoutube('live')">Live</li>
</ul>
</form>
</div>
</body>
</html>
我是JS的新手,所以如果我犯了任何错误的错误,请告诉我!
答案 0 :(得分:0)
我会删除内联javascript并使用在init
回调中创建的委派点击事件。问题可能是由于时间问题,这条路线避免了这个问题。此外,由于<li>
的所有文本都是搜索字词,因此您可以使用它来获取应搜索的内容。所以:
<ul class="youtube-categories" id="youtube-category">
<li>Music</li>
<li>Sports</li>
<li>Gaming</li>
<li>Movies</li>
<li>TV Shows</li>
<li>News</li>
<li>Live</li>
</ul>
更新了javascript:
function init() {
gapi.client.setApiKey("API KEY");
gapi.client.load("youtube","v3",function(){
document.querySelector('#youtube-category').addEventListener('click', function(event) {
// it's an <li> tag, get the text and search with it
if(event.target.tagName === 'LI') {
var searchTerm = event.target.textContent.toLowerCase();
var request = gapi.client.youtube.search.list({
part: 'snippet',
type: 'video',
q: searchTerm
});
console.log(searchTerm);
request.execute(function(response){
console.log(response);
});
}
}, false);
});
}