简体   繁体   English

JavaScript在按钮点击时加载页面

[英]JavaScript load a page on button click

I am trying to do a very simple task here, I would like to be able to click a button on a page and have it take me to another page. 我想在这里做一个非常简单的任务,我希望能够点击页面上的一个按钮,让它带我到另一个页面。 I have tried window.location.href, and a bunch of other things and it does nothing. 我已经尝试过window.location.href,以及其他一些东西,它什么也没做。 I have tried different platforms and different browsers, all with the same result. 我尝试过不同的平台和不同的浏览器,都有相同的结果。

I know that it can call a function but I just cannot get the new page to load. 我知道它可以调用一个函数,但我只是无法加载新页面。 Also this is all in my local file system and both pages live at the same level (but I have also tried to load an external page like www.apple.com). 此外,这一切都在我的本地文件系统中,并且两个页面都处于同一级别(但我也尝试加载外部页面,如www.apple.com)。

Any thoughts? 有什么想法吗?

Thanks Patrick 谢谢Patrick

Simple code to redirect page 简单的代码重定向页面

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

Don't abuse form elements where <a> elements will suffice. 不要滥用<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>

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

You can try it by typing it into your address bar as well, eg javascript: window.location = "http://www.google.com/" . 您也可以在地址栏中输入它来尝试,例如javascript: window.location = "http://www.google.com/"

Also note that the protocol part of the URL ( http:// ) is not optional for absolute links; 另请注意,URL( http:// )的协议部分对于绝对链接不是可选的; omitting it will make javascript assume a relative link. 省略它将使javascript假设一个相对链接。

The answers here work to open the page in the same browser window/tab. 此处的答案可用于在同一浏览器窗口/选项卡中打开页面。

However, I wanted the page to open in a new window/tab when they click a button. 但是,我希望页面在单击按钮时在新窗口/选项卡中打开。 (tab/window decision depends on the user's browser setting) (标签/窗口决定取决于用户的浏览器设置)

So here is how it worked to open the page in new tab/window : 以下是在新选项卡/窗口中打开页面的工作原理:

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

It doesn't have to be a button, you can use anywhere. 它不必是一个按钮,你可以在任何地方使用。 Notice the _blank that is used to open in new tab/window. 注意用于在新选项卡/窗口中打开的_blank

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM