javascript - 搜索谷歌的输入

标签 javascript html google-chrome-extension google-chrome-theme

我正在为我的 Chromebook 制作一个扩展主题,用于搜索编码网站(如本网站、w3schools 等),我该如何制作它?这是我到目前为止的代码:

<html>
<head>
</head>
<body>    
<input id="input1">
<button onclick="searchGoogle()">Search Google</button>
<script>
function searchGoogle() {
        var one = document.getElementById("input1").value;
        var two = 'http://www.google.com/search?q=' + one;
        window.location = two;
    }
</script>
</body>
</html>

我的代码不起作用

运行时,会弹出:

(Image of my code running)

我的代码有错吗?

我们将不胜感激任何帮助。

编辑

<html>
<head>
<script src="searchgoogle.js">
</script>
</head>
<body>    
<input id="input1">
<button id="link">Search Google</button>

</body>
</html>

document.addEventListener('DOMContentLoaded', function() {
    var link = document.getElementById('link');
    // onClick's logic below:
    link.addEventListener('click', function() {

        function searchGoogle() {
        var one = document.getElementById("input1").value;
        var two = 'https://www.google.com/search?q=' + one;
        window.location = two;
    }


    });
});

也没用

最佳答案

您在监听器函数中声明了函数 searchGoogle,但它从未被调用。尝试使用:

document.addEventListener('DOMContentLoaded', function() {
    var link = document.getElementById('link');
    // onClick's logic below:
    link.addEventListener('click', function() {

        //there is no need to declare a new function here.

        var one = document.getElementById("input1").value;
        var two = 'https://www.google.com/search?q=' + encodeURIComponent(one);
        window.location = two;



    });
});

关于javascript - 搜索谷歌的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50495108/

相关文章:

Javascript - 将数组 1 中的子字符串与数组 2 中的字符串进行比较 > 如果存在多个实例,则丢弃

javascript - 传递文档正文而不在网络 worker 中编辑它

javascript - 如何在不使用 Canvas 的情况下通过 OOP 创建一个圆圈?

jquery - 使用具有非固定高度/宽度容器的流沙

javascript - Chrome 扩展程序 : executeScript after window is loaded

google-chrome - Chrome 字符替换

javascript - 带有固定标题的 HTML 表格?

html - 如何使用来自 Controller 的参数调用函数进入 View 以及如何将该函数绑定(bind)到angularjs中的指令

html - 粘性导航栏不粘

javascript - Chrome 内容和后台脚本能否共享对 blob : URLs? 的访问权限