作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
当访问者点击按钮元素时,如何更改 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/
我是一名优秀的程序员,十分优秀!