Chrome 为什么html不能读取这个JavaScript函数?

5ssjco0h  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(141)

我试图重新创建谷歌主页,但我的问题是,当我按下我感觉幸运按钮时,我感觉幸运按钮的功能luck()没有被识别。
错误代码:
未捕获的TypeError TypeError:运气不是一种功能
我的代码:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Search</title>
        <link rel="stylesheet" href="style.css">
        <script type="text/javascript" src="combinados.js"></script>
        <script type="text/javascript">
            function luck() {
                var query = document.querySelector(".search").value;
                window.location.href = "https://www.google.com/search?q=" + encodeURIComponent(query) + "&btnI";
            };
         </script>

    </head>
    <body >
        <form class="bar" action="https://www.google.com/search">
            <input class="search" type="text" name="q">
            <input id ="search" type="submit" value="Google Search">
            <input id ="luck" type="button" value="I am feeling lucky" onclick="luck()">
            
        </form>
        <ul id="links">
            <li><a href="imagesearch.html">Image Search </a></li>
            <br>
            <li><a href="advancedsearch.html">Advanced Search </a></li>
        </ul>
    </body>
</html>

为什么这个代码不起作用?

eyh26e7m

eyh26e7m1#

在你的代码中,你有<input>的id,函数名也是一样的。因此,当单击按钮时,浏览器尝试执行luck()函数,但有一个ID为luck的HTML元素,这会造成混淆。
要解决这个问题,您可以更改函数名称或<input> id。
下面是一个例子,我将函数名改为feelingLucky()

<input id="luck" type="button" value="I am feeling lucky" onclick="feelingLucky()">
function feelingLucky() {
    var query = document.querySelector(".search").value;
    window.location.href = "https://www.google.com/search?q=" + encodeURIComponent(query) + "&btnI";
};

相关问题