我创建了一个应用程序,允许用户检索 Youtube 上观看次数最多的视频。我想包括一个验证功能,提醒用户他们需要在搜索栏上输入内容,以及一个清除所有搜索结果和搜索栏上的输入的功能。我是 JavaScript 的新手,所以我一直在思考如何在我的代码中包含这些函数。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="crossorigin="anonymous"></script>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<input id="query" placeholder="Enter video right here" type="text"/>
<button onclick="search()">Search</button>
<pre id="response"></pre>
</body>
</html>
<!--Code from tpl/item.html-->
<div class="item">
<h2>{{title}}</h2>
<iframe class="video w100" width="640" height="360" src="//www.youtube.com/embed/{{videoid}}" frameborder="0" allowfullscreen></iframe>
</div>
最佳答案
function that will alert the user that they need to enter the input on the search bar
在您的 search() 函数中,添加一个条件来检查是否已输入值。如果为真,请运行您列出的代码。如果为 false,则 alert()。
function search(){
if(document.getElementById('query').value.trim().length > 0){
// your code
} else {
alert('please enter a value into the search');
}
}
function that will clear all of the search results and the input on the search bar
要清除元素的任何值或内部 HTML,请将 element.value 或 element.innerHTML 设置为空。示例:
document.getElementById('query').value = '';
document.getElementById('response').innerHTML = '';
关于JavaScript Youtube Search API v3 : Clear Results, 和验证函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54395381/