Javascript 按钮重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12521491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:36:24  来源:igfitidea点击:

Javascript Button Redirect

javascripthtml

提问by Geekender

Trying to get my button to act like a link (tried the <A>tag and it would work if you open in a new tab but not if you click on it. Then tried this code and nothing. Suggestions?

试图让我的按钮表现得像一个链接(尝试了<A>标签,如果你在新标签页中打开它会起作用,但如果你点击它就不会起作用。然后尝试了这段代码,什么也没做。建议?

<button onClick="location.href='/secure/edit.aspx?id=671'">Edit</button>

回答by Oliver Moran

You need to explicitly say window.locationbecause thisin the context of the button is the button object itself. Ordinarily, JavaScript is run in the context of the windowobject, so you don't need to do that.

您需要明确说明,window.location因为this在按钮的上下文中是按钮对象本身。通常,JavaScript 在window对象的上下文中运行,因此您不需要这样做。

<button onClick="javascript:window.location.href='/secure/edit.aspx?id=671'">Edit</button>

(Additionally, I also like to explicitly state that the script is javascript:, but that's purely a personal thing.)

(此外,我还想明确指出脚本是javascript:,但这纯粹是个人的事情。)

回答by AlienWebguy

<button onclick="window.location='/secure/edit.aspx?id=671'">Edit</button>

回答by Tarsis Azevedo

Try with window.location

尝试使用 window.location

<button onClick="window.location='/secure/edit.aspx?id=671'">Edit</button>

回答by Nixon

Add type = "button"

添加 type = "button"

<button type = "button" onClick="window.location='/secure/edit.aspx?id=671'">Edit</button>

You need to add the type, otherwise the button will act as a submit button and will POST your form instead of redirecting to the desired url.

您需要添加type,否则该按钮将充当提交按钮并发布您的表单,而不是重定向到所需的 url。