我应该使用哪些元素进行JavaScript操作?
执行播放/暂停/停止/新建/打开/保存/打印/关闭等操作
<a id="play" href="#">Play</a>
<a href="#play">Play</a>
<button id="play" tabindex="0">Play</button>
<div id="play" role="button" tabindex="0">Play</div>
我看到很多人使用锚点<a>
和href="#"
,但是感觉不是非常语义,感觉锚是针对指向资源的超链接,而不是用于执行操作的超链接东西。然后你必须用event.preventDefault
(即return false
)来破解它。
我很少看到人们使用<button>
元素,但它不是应该使用的内容吗?
答案 0 :(得分:3)
确定哪个元素具有基于JS的用户交互的最佳语义的最佳方法是询问在JS失败时您想要发生什么(which it will。
思考progressive enhancement。想想unobtrusive JavaScript。
用户是否应该转到其他页面?使用链接。 href
将是JS失败时的后备。
用户在发送一些数据或发出POST请求时是否应该转到另一页?使用按钮,将其放在表格中。
不可能有任何类型的服务器回退吗?使用<button type="button">
并考虑从JS / DOM而不是HTML生成它。
答案 1 :(得分:1)
这是一种偏好,并且更多一点。
这是一条经验法则:
href
属性。href
!考虑这段代码。
const anchor = document.getElementsByTagName('a')[0]
const button = document.getElementsByTagName('button')[0]
anchor.addEventListener('click', e => {
console.log('anchor clicked')
e.preventDefault()
}, false)
button.addEventListener('click', e => {
console.log('button clicked')
})
&#13;
a {
text-decoration: none;
padding: 2px;
}
button {
background: none;
border: none;
font-size: 16px;
}
.btn {
background-color: blue;
color: white;
display: inline-block;
text-align: center;
}
&#13;
<a class="btn" href="#">
Anchor
</a>
<hr/>
<button class="btn" type="button">
Button
</button>
&#13;
<强>定型强>
它们看起来几乎相似(只有极少的理由)唯一的问题是你必须撤消button
附带的某些样式,如border
&amp; background
{但是有了锚点,你不会得到你用按钮获得的点击弹出动画。
<强>功能强>
但是由于主持人<a>
需要<a href="some/path">
才能工作,即使它只是#
,除非您需要在点击主播后进行导航您必须在javascript中使用e.preventDefault()
来阻止它。
我认为除了造型之外,还有更多内容。功能。
它只是一个程序员来思考它们,并且最好注意细节,因为button
需要特定的类型属性才能使其正常工作始终< / strong>&amp;锚需要e.preventDefault()
。
答案 2 :(得分:-1)
然后你必须使用event.preventDefault
来破解它
你可以将href设置为javascript:void(0)
而不是#,这会阻止执行而不必使用event.preventDefault()
但按钮可能更适合这种事情
答案 3 :(得分:-2)
这更像是一种偏好。
就个人而言,我更喜欢使用&lt; button&gt;标记或制作我自己的。
如果您更有意义使用&lt; button&gt;标签,使用它。如果它有效,那没关系。 =)