当访问者点击按钮元素时,如何更改网址?
示例:
<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>
对于快速演示页面,我只需要在访问者点击按钮时将其发送到新的URL。我可以执行JavaScript onclick(在Alert Hi按钮中),如果我从Firebug的控制台执行window.location.href='http://www.google.com/'
,则URL会发生变化。如何更改按钮单击时的URL?
答案 0 :(得分:12)
问题是当您单击按钮时正在提交表单。添加type="button"
以便它不会提交表单。您在javascript
属性中也不需要onclick
。见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>
答案 1 :(得分:-2)
<button onclick="javascript:window.location='http://www.google.com/'">Go to Google</button>
只需删除您的.href即可正常使用