JavaScript在按钮点击时加载页面

Pat*_*ick 62 javascript load button

我想在这里做一个非常简单的任务,我希望能够点击页面上的一个按钮,让它带我到另一个页面.我已经尝试过window.location.href,以及其他一些东西,它什么也没做.我尝试过不同的平台和不同的浏览器,都有相同的结果.

我知道它可以调用一个函数,但我只是无法加载新页面.此外,这一切都在我的本地文件系统中,并且两个页面都处于同一级别(但我也尝试加载外部页面,如www.apple.com).

有什么想法吗?

谢谢Patrick

Pra*_*ana 89

简单的代码重定向页面

<!-- html button designing and calling the event in javascript -->
<input id="btntest" type="button" value="Check" 
       onclick="window.location.href = 'http://www.google.com'" />
Run Code Online (Sandbox Code Playgroud)


BGe*_*sen 22

不要滥用<a>元素就足够的表单元素.

<style>
    /* or put this in your stylesheet */

    .button {
        display: inline-block;
        padding: 3px 5px;
        border: 1px solid #000;
        background: #eee;
    }

</style>

<!-- instead of abusing a button or input element -->
<a href="url" class="button">text</a>
Run Code Online (Sandbox Code Playgroud)


tda*_*ers 18

只是window.location = "http://wherever.you.wanna.go.com/",或者,对于本地链接,window.location = "my_relative_link.html".

您也可以通过在地址栏中输入它来尝试,例如javascript: window.location = "http://www.google.com/".

另请注意,URL(http://)的协议部分对于绝对链接不是可选的; 省略它将使javascript假设一个相对链接.


Tar*_*rik 5

这里的答案适用于在同一浏览器窗口/选项卡中打开页面。

但是,我希望当他们单击按钮时页面在新窗口/选项卡中打开。(选项卡/窗口决定取决于用户的浏览器设置)

以下是在新选项卡/窗口中打开页面的工作原理:

<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>
Run Code Online (Sandbox Code Playgroud)

它不一定是一个按钮,您可以在任何地方使用。请注意用于在新选项卡/窗口中打开的_blank 。