Javascript Onclick 或 href 最适合在按钮中打开链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10765363/
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
Onclick or href which is best for opening an link in button
提问by Ballu Rocks
Which is the best method.To open an link using button
这是最好的方法。使用按钮打开链接
<button type="button" onclick="location='permalink.php'">Permalink</button>
<button type="button" href="index.php">Permalink</button>
回答by Vlad Balmos
If you use jquery you can write the second button like this
如果您使用 jquery,您可以像这样编写第二个按钮
<button type="button" id="SecondButton" data-href="index.php">Permalink</button>
and then add some javascript:
然后添加一些javascript:
<script type="text/javascript">
$('#SecondButton').click(function(e) {
e.preventDefault(); e.stopPropagation();
window.location.href = $(e.currentTarget).data().href;
});
</script>
Edit (Further completed scenarios)
编辑(进一步完成的场景)
<button type="button" id="SecondButton" data-href="index.php" onclick="location='permalink.php'" href="index.php">Permalink</button>
I would insert both additional href tag and onclick inside it too; you could then test for different scenarios; devices that do not support javascript or jquery fails to load on CDN like mobile etc:
我也会在其中插入额外的 href 标签和 onclick ;然后你可以测试不同的场景;不支持 javascript 或 jquery 的设备无法在移动设备等 CDN 上加载:
<button type="button" id="SecondButton" data-href="index.php?trackAnalytics=1" onclick="location='permalink.php?trackAnalytics=2'" href="index.php?trackAnalytics=3">Permalink</button>
回答by Joseph
The first one should work, but inline scripts are not recommended. You should read about how to attach events using addEventListener
for standards compliant browsers and attachEvent
for older IE.
第一个应该可以工作,但不建议使用内联脚本。您应该阅读有关如何使用addEventListener
符合标准的浏览器和attachEvent
旧版 IE附加事件的信息。
The second won't work since buttons don't use the href
attribute.
第二个不起作用,因为按钮不使用href
属性。
回答by LawMan
If you are using bootstrap, you can do this...
如果您使用的是引导程序,则可以执行此操作...
<a class="btn btn-default" href="permalink.php">Permalink</a>
回答by c24w
Alternatively, you can do something like this, if the button 'style' is what you're after, and not specifically the <button>
tag:
或者,你可以做这样的事情,如果按钮“样式”是你所追求的,而不是专门的<button>
标签:
<form method="link" action="permalink.php">
<input type="submit" value="Permalink">
</form>
Another thought is that you could style an anchor to look like a button, then you could use the href attribute.
另一个想法是,您可以将锚点设置为看起来像按钮,然后您可以使用 href 属性。