< button onclick = ...>有什么区别?和< a href =“#" onclick = .../> [英] what is the difference between <button onclick=...> and <a href="#" onclick=.../>
问题描述
我发现很多时候页面都使用"a"标签,并且希望使其像按钮一样.就像这样:
I find many times the pages use "a" tag and want to make it like a button. it's something like this:
<a href="#" class="button" onclick="...." />
我对为什么不只使用按钮"标签感到困惑?像这样:
I'm confusing about why not just use "button" tag? like this:
<button onclick="....">button</button>
两者之间有什么区别? 我真的很想学习,谢谢!
what is the difference between? I really want to learn it, thanks!
还有一个情况问题:
三个类似于按钮的< a>标记",如下所示:
Three "button-like < a > tag" as below:
提示:
- 不同的一次调用ajax,然后获得不同的期间记录
- 需要使用onclick ="location.replace()",因为要顺利返回上一页.
原始代码:
<a href="url" class="btn" >Today</a>
我已更改为:
<a href="#" onclick="location.replace(url)" class="btn" >Today</a>
考虑以下事项:
<button onclick="location.replace(url)">Today</button>
在这种情况下您会怎么做?使用按钮标记是否有误?
What will you do in this situation? Is any incorrect to use button tag ?
推荐答案
这基本上是历史文物.
它源自将自定义样式应用于锚点要容易得多的时候.通过在锚点本身内使用更多元素,您可以轻松构建自动调整大小的按钮式"锚点.
It stems from the time when it was much easier to apply custom styling to an anchor. You could easily build auto-sized "button-looking" anchors by using more elements inside the anchor itself.
如今,借助增强的CSS选项和更好的浏览器兼容性,这是不必要的.如果button
是正确的语义元素,则没有理由改用a
.
Today, with enhanced CSS options and better browser compatibility, this is not necessary. When button
is the correct semantic element, you have no reason to use a
instead.
因此,请使用锚点链接到其他页面.它应始终具有href
,而不是仅使用#
和onclick
.现在,您仍然可以使用onclick
-只需确保href
将您定向到与onclick
相同的数据即可.当您想让搜索机器人导航您的网站时,这非常方便,即使实际用户会看到例如响应速度更快的界面(例如,通过AJAX下载更新的内容).确保在新窗口/选项卡中打开链接的常用方法仍然有效(按ctrl + click,右键单击和单击中键都不应该执行onclick
动作).
So, use anchors for links to other pages. It should always have a href
, rather than just using #
and onclick
. Now, you can still use onclick
as well - just make sure that the href
directs you to the same data that onclick
does. This is very handy when you want to have a way for search bots to navigate your site, even though the actual users will be presented with e.g. a more responsive interface (for example, downloading the updated content through AJAX). Make sure that common methods of opening the link in a new window / tab still work (neither of ctrl+click, right-click and middle-click should execute the onclick
action).
按钮是与您当前所在的页面进行交互的元素,无论这意味着进行客户端脚本编写或向服务器发送表单.
Buttons are the elements that are there to interact with the page you're currently on, whether that means doing client-side scripting, or sending a form to the server.
编辑:
通过对问题的编辑,很明显,您应该简单地使用具有普通href
的锚点.没有理由使用onclick
或button
,而您 只是建立了一个简单的超链接,这就是锚点的作用.
With the edit to your question, it's obvious you should simply use an anchor with a normal href
. There's no reason to use either onclick
or a button
, and you are just making a simple hyperlink, that's what anchors are for.
这篇关于< button onclick = ...>有什么区别?和< a href =“#" onclick = .../>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!