我必须使用<a> tag? Can I not just use .click()?

时间:2016-07-09 18:40:04

标签: javascript jquery html5 click href

I'm using jQuery and jQuery mobile and I've always leaned towards making clickable events with button/a tags

<button id='id'>my button</button>
<a href='#' id='id2'>my anchor</a> 

I read somewhere that this was previously the recommended standard, but that limit has since been deprecated.

My understanding is the following is not just acceptable, but does not break standards

<h1 id="id">abcdef</h1>

<script>
$("#id").click(myFunction);
</script>

Am I right? Is it acceptable for me to just apply click events to any tag I want to? (I expect/demand my clients to be less than 3years old)

2 个答案:

答案 0 :(得分:3)

虽然您可以将click事件处理程序附加到大多数元素,但我建议您坚持将它们附加到abutton或用户的任何其他元素期待点击,即。不是tablestrong

这有两个原因。首先,因为它是人们所期望的,并且拥有一个用户轻松导航和操作的UI,而不用思考他们需要做什么是至关重要的。用户不会认为大标题是可点击的,因此最终可能会隐藏一些他们需要使用的功能。

其次,通过将事件保留在标准可点击元素上,您既可以遵守可访问性指南,也可以在JS代码无法工作或客户端浏览器禁用时提供优雅冗余。

当然有例外情况,但作为一般规则,我坚持这样做。

答案 1 :(得分:0)

只要它有效,我会说继续做下去。只是保持一致。

一般来说,我会说是的,您可以将点击事件应用于您想要的任何内容;请记住,虽然此功能因浏览器而异。我似乎记得在我生命中的某个时刻尝试让div接收点击事件时遇到很多麻烦。

我喜欢标题标签上的按钮和锚标签。锚标签可以标签,通常描述某些东西的链接。标题标签通常更多用于组织页面中的内容而不是交互元素。