HTML 输入类型图像点击后不会重定向?
我有以下代码,工作正常:
<input type="button" name="btnHello" value="Hello" onclick="Test();"/>
这是 JS 函数:
function Test() {
window.location.href = "Page2.aspx";
}
当我单击“Hello”按钮时,它会像预期的那样重定向到 Page2.aspx。但是当我将按钮更改为图像按钮时:
<input type="image" src="images/myimage.jpg" name="btnHello" onclick="Test();"/>
它不再起作用。页面回发,但更像是刷新。我可以在 JS 函数中放置一个警报以查看它正在被调用,但我不确定为什么重定向不起作用?有人经历过吗?
我知道这可能很愚蠢,但我很困惑。
非常感谢!
I have the following code, which works fine:
<input type="button" name="btnHello" value="Hello" onclick="Test();"/>
and here is the JS function:
function Test() {
window.location.href = "Page2.aspx";
}
When I click my Hello button, it redirects to Page2.aspx like expected. But when I change my button to an image button:
<input type="image" src="images/myimage.jpg" name="btnHello" onclick="Test();"/>
It no longer works. The page posts back, but its more like a refresh. I can put an alert in the JS function to see that it is getting called, but I'm not sure why the redirect doesn't work? Has anyone ever experienced this?
I know its probably something stupid, but I'm stumped.
Many thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要从事件处理程序中
返回 false
以阻止默认操作。但是,由于您一开始就不希望它回发,因此您不妨使用普通的
而不是
.
You need to
return false
from the event handler to prevent the default action.However, since you don't want it to postback in the first place, you might as well use an ordinary
<img />
instead of an<input />
.由于您正在进行回发,因此重定向被取消。添加返回假;在函数 test() 之后;
例如
The redirect is getting cancelled because you are doing a postback. Add return false; after the function test();
e.g
尝试使用
img
标签:Try using an
img
tag:输入类型图像没有 onclick 事件。您需要改用 img 标签。
input type image does not have a onclick event. You need to use the img tag instead.
<img onclick="Test();">