【问题标题】:HTML and JavaScript make search input ready for URLHTML 和 JavaScript 使搜索输入为 URL 做好准备
【发布时间】:2013-12-31 03:40:22
【问题描述】:

我正在制作一个网页,以便可以从自定义页面搜索 google。 但是当我点击搜索时,它会在谷歌上搜索我的输入,但是当我输入 # 和 % 以及所有这些字符时,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();
        }
    );

【问题讨论】:

  • 您需要对搜索文本进行编码。有一个方便的 Javascript 函数可以做到这一点,看看encodeURIComponent

标签: javascript html url search-engine google-search


【解决方案1】:

使用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());
});

【讨论】:

  • 我什至不会提到您的 or 解决方案,因为在这种情况下它有点逊色,因为您需要附加基本 URL。
【解决方案2】:

使用函数encodeURIComponent:

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

希望对你有帮助:)

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      相关资源
      最近更新 更多