javascript:协议(protocol)很糟糕,但最方便的替代方案是什么?

标签 javascript events accessibility

所以我想大家一致认为使用 href="javascript:fn_name();"是不好的做法。但是假设我有一个链接:<a href="#" class="exec-fn">Click me</a> .

我可以用

$('.exec-fn').click(fn_name);

但这不是很方便。因为它是一个点击事件,所以这不适用于点击,或者,也许,跳转到链接并按 Enter 键跟随它。我有点想模仿浏览器的焦点和跟随链接的能力,因为它的默认行为允许它,但我知道 javascript:不推荐协议(protocol),我也不总是想命名一个全局可访问的函数。

有没有更好的方法?

最佳答案

有相应的推荐:
http://www.w3.org/TR/DOM-Level-3-Events/#click-synthesis

If the instance of the activation trigger is not an event of event type click (that is, when it does not result from a user's activation of a button or link using a mouse or equivalent pointing device), the implementation MUST synthesize and dispatch an event of event type click as one of the default actions of that activation trigger. The value of the Event.target MUST be set to the event target (normally, the currently focused element), and the event MUST simulate a left click (i.e., the MouseEvent.button attribute value MUST be 0, and the MouseEvent.buttons attribute value MUST be 1). Other context information of such a simulated click event is implementation dependent, but for historical purposes, the interface for the click event MUST be the MouseEvent interface, regardless of the actual device used to activate the element. Preventing the default action of the activation trigger, such as with the Event.preventDefault(), MUST stop the initiation of the activation behavior.

还有一个例子:

When a user activates a hyperlink using a keyboard, such as by focusing the hyperlink element and pressing the 'Enter' or ' ' key, a click event would be dispatched as the default action of the respective keydown event.

基本上,点击事件是一种可行的方法。

关于javascript:协议(protocol)很糟糕,但最方便的替代方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22676182/

相关文章:

ios - 如何在动态类型的 UIContentSizeCategoryDidChangeNotification 之后更新约束

javascript - 在 for 循环中将一行放入前景

c# - 事件词典

javascript - 有没有办法在 AngularJS 中同时订阅多个事件?

c# - 阻止鼠标光标水平移动,但仍想捕获 MouseMove 事件

javascript - 当当前焦点元素从 DOM 中移除时,如何挽救焦点?

xhtml - 哪个替代文本最适合屏幕阅读器,例如 "smiling kid"?

c# - Javascript 无法在内容中运行

javascript - 尝试在 Jasmine 规范文件中导入类时获取 "SyntaxError: Cannot use import statement outside a module"

javascript - 在 javascript 循环中添加多个 HTML 元素