【问题标题】:How to make custom search engine that on enter it goes to google and searches for what the user has inputed using html and javascript如何使自定义搜索引擎在输入时转到谷歌并搜索用户使用 html 和 javascript 输入的内容
【发布时间】:2022-01-21 10:53:51
【问题描述】:

我不太擅长 html 或 javascript,但我认为制作它会很酷,这样每次我打开一个新标签时,它都是我自己搜索的东西或其他东西。我遇到的问题是当我按下回车键时搜索它,但它从来没有用过,我尝试了很多东西,但没有一个有效。老实说,即使我在高中上了一堂关于 html 的课,我也几乎不知道自己在做什么。这是我的代码。

HTML

    const q = document.getElementById('query');
    const google = 'https://www.google.com/search?q='
    
    
    
    document.addEventListener("keyup", function(event) {
      
        if (event.keyCode === 13) {
         
         const url = google + q.value;
         const win = window.open(url, '_blank'); 
            win.focus();
            alert("test");
                  
        }
    });
body{
background-color: black;
}
    <section>
        <div class="searchBx">
            <input id="query" type="text" class="query" value="" style="background-color:white; color: black; border: none; border-width:0px; text-align:center "/>    

        </div>

【问题讨论】:

  • 您的 javascript 正在抛出异常,请修复这些异常,以便其他人可以轻松看到您要执行的操作。

标签: javascript html css web


【解决方案1】:

如果您这样输入,您的代码将起作用。

<style>
    .search-box{
        background-color:white;
        color: black; 
        border: none;
        border-width:0px;
        text-align:center;
        border:solid 1px #555555;
    }
</style> 

<input type="text" class="search-box" onchange = "search(this.value);" placeholder="Type your question?">    
<script>
    if(q==""){
        return false;
    }
    function search(q){
    let Link  = 'https://www.google.com/search?q='+q;
    window.open(Link, '_blank');  
    }
</script>

【讨论】:

  • 这不起作用
  • 我的错!函数行应该在第一行:
【解决方案2】:

我的错! 功能行应该在第一行。请使用以下更正后的代码:

   <script>
          function search(q){
                 if(q==""){
                        return false;
                 }
        
                 let Link  = 'https://www.google.com/search?q='+q;
                 window.open(Link, '_blank');  
          }
   </script>

【讨论】:

  • 如果您只是想修改以前的答案,请不要发布单独的答案 - 使用编辑功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
  • 2019-06-28
  • 2020-03-27
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多