HTML 和 JavaScript 使搜索输入为 URL 做好准备

HTML and JavaScript make search input ready for URL

本文关键字:URL 输入 JavaScript 搜索 HTML      更新时间:2023-09-26

我正在制作一个网页,以便我可以从自定义页面搜索谷歌。但是当我单击搜索时,它会在谷歌上搜索我的输入,但是当我输入#和%以及所有这些字符时,URL应该不同。所以我的问题是如何转换这样的东西:

http://www.google.com/#q=Hello World C#

对此:

http://www.google.com/#q=HEllo+world+C%23

使用 JavaScript

编辑:这是我尝试使用的功能

    $('button#SubmitSearch').click
    (
        function()
        {
            window.location = encodeURIComponent("https://www.google.nl/#q=" + $('input#SearchBar').val());
        }
    );

    $('button#SubmitSearch').click
    (
        function()
        {
            window.location = "https://www.google.nl/#q=" + $('input#SearchBar').val();
        }
    );

使用 encodeURI,例如

console.log(encodeURI('http://www.google.com/#q=Hello World C#'));
> "http://www.google.com/#q=Hello%20World%20C#"

或encodeURIComponent

console.log(encodeURIComponent('Hello World C#'));
> "Hello%20World%20C%23"

从您的 OP :

$('button#SubmitSearch').click(function(){
    window.location = "https://www.google.nl/#q=" + encodeURIComponent($('input#SearchBar').val());
});

使用函数encodeURIComponent:

encodeURIComponent('this is a string with special characters like # and ?')

希望对:)有所帮助

试试这个Var search = document.getElementById("searchbox");然后使用 addeventlistener 或 onClick

key=key.replace(//g,"+"); document.location("http://google.com/#q" + search.value);