gpt4 book ai didi

javascript - 如何在访问者单击按钮时更改页面的 URL?

转载 作者:搜寻专家 更新时间:2023-11-01 04:52:33 25 4
gpt4 key购买 nike

当访问者点击按钮元素时,如何更改 URL?

例子:

<form id="search">
<input type="text" />
<button onclick="javascript:alert('hi');">Alert Hi</button>
<button onclick="javascript:window.location.href='http://www.google.com/'">Go to Google</button>
</form>

( Or see JSFiddle .)

对于快速演示页面,我只需要在访问者单击按钮时将他们发送到一个新的 URL。我可以执行 JavaScript onclick(在 Alert Hi 按钮中),如果我从 Firebug 的控制台执行 window.location.href='http://www.google.com/',URL 会发生变化。我需要做什么才能在单击按钮时更改 URL?

最佳答案

问题是当您单击按钮时正在提交表单。添加 type="button" 这样它就不会提交表单。您也不需要 onclick 属性中的 javascript。参见 How to prevent buttons from submitting forms

示例 http://jsfiddle.net/E7UEe/1/请注意,它不会转到 google.com,因为 jsfiddle 不允许它。请注意错误消息 Refused to display document because display forbidden by X-Frame-Options.

<form id="search">
<input type="text" />
<button onclick="javascript:alert('hi');">Alert Hi</button>
<button type="button" onclick="window.location.href='http://www.google.com/'">Go to Google</button>
</form>​

没有 JS 的替代方法是 appearance:button CSS directive http://jsfiddle.net/d6gWA/

<a class="btn"> Link looking like button</a>​
.btn {
appearance: button;
-moz-appearance: button;
-webkit-appearance: button;
-ms-appearance: button;
}​

或者您总是可以将按钮放在链接中 http://jsfiddle.net/d6gWA/2/

<a class="btn" href="http://www.google.com" target="_blank"><button type="button">Link Button</button></a>​

关于javascript - 如何在访问者单击按钮时更改页面的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13425833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com