0

我正在为我的 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>

我的代码不起作用

当它运行时,会弹出:

(我的代码运行的图像)

我的代码错了吗?

任何帮助将不胜感激。

编辑

<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;
    }


    });
});

也没有工作

4

1 回答 1

1

您在侦听器函数中声明该函数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;



    });
});
于 2018-05-23T18:55:37.410 回答