JavaScript Youtube 搜索 API v3:清除结果和验证功能

JavaScript Youtube Search API v3: Clear Results, and Validation function

我创建了一个应用程序,允许用户检索 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() 函数中,添加一个条件来检查是否已输入值。如果为真,运行 您列出的代码。如果为假,则 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 = '';

HTML:

<div class="search-wrap">
    <input id="query" placeholder="Enter video right here" type="text"/>
    <button onclick="search()">Search</button>
    <pre id="response"></pre>
</div>

JS:

$(document).ready(function() {
    // get submit button DOM
    const buttonSubmit = $('yourSubmitButton');
    // when you click the submit button
    buttonSubmit.click(function() {
        const searchValue = $(this).parent('.search-wrap').find('#query').val();
        if(searchValue === '') {
            alert('You must input something');
            return false;
        } 

        /* Do whatever you want in here*/
        search();

        /* clear result after search */
        $(this).parent('.search-wrap').find('#query').val('');
    })
})

我将您的 HTML 代码包装在“.search-wrap”中,如果需要,请使用 jQuery。更多信息搜索 jQuery DOM 树遍历