Javascript 使用JS文件而不是HTML事件处理程序重定向?

Javascript 使用JS文件而不是HTML事件处理程序重定向?,javascript,jquery,html,events,onclick,Javascript,Jquery,Html,Events,Onclick,因此,目前我希望将javascript放在附加的JS文件中,而不是使用附加到HTML对象的“OnClick”函数。到目前为止,我已经: <html> <head> </head> <body> <h1 id = '5' class = ''>6</h1> <button id = '7' class = ''>8</button>

因此,目前我希望将javascript放在附加的JS文件中,而不是使用附加到HTML对象的“OnClick”函数。到目前为止,我已经:

<html>
    <head>       
    </head>
    <body>
        <h1 id = '5' class = ''>6</h1>
        <button id = '7' class = ''>8</button>
        <script src = 'js/9.js'></script>
    </body>
</html>
然后重定向到另一个页面。关于如何改进这一点,有什么建议吗

  • 请使用字符串作为ID。我知道您现在可以使用数字,但不推荐使用
  • 使用加载事件处理程序
  • 如果没有给按钮指定类型,则可能是将页面提交给自己,因此返回false或preventDefault
  • 属性中围绕=的间距是什么?没有必要也不推荐
  • 像这样

    <html>
        <head>       
            <script src="js/9.js"></script>
        </head>
        <body>
            <h1 id="five" class="">6</h1>
            <button id="seven" class="">8</button>
        </body>
    </html>
    

    如果使用jQuery,它将是

    <html>
        <head>       
            <script src="js/jquery.js"></script>
            <script src="js/9.js"></script>
        </head>
        <body>
            <h1 id="five" class="">6</h1>
            <button id="seven" class="">8</button>
        </body>
    </html>
    
    最后,您根本不需要脚本:

    <form action="page2.html">
      <button type="submit" id="seven" class="">8</button>
    </form>
    
    
    8.
    
    您正在使用jQuery吗?(如标签所示)如果你把这个按钮放在一个带有动作的表单中,它会自动重定向所有内容。看一下表单和jquery选项,它们都很有用。啊,也谢谢你的时尚提示。我将继续提供新的信息。非常感谢。
    <html>
        <head>       
            <script src="js/jquery.js"></script>
            <script src="js/9.js"></script>
        </head>
        <body>
            <h1 id="five" class="">6</h1>
            <button id="seven" class="">8</button>
        </body>
    </html>
    
    $(function() {
      $("#seven").on("click",function (e) {
        e.preventDefault();
        location.replace("page2.html"); // or just location="page2.html";
      });
    });
    
    <form action="page2.html">
      <button type="submit" id="seven" class="">8</button>
    </form>