我正在为我的 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;
}
});
});
也没用
最佳答案
您在监听器函数中声明了函数 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/