将事件绑定到<img/>或<a>?

时间:2016-01-13 15:29:10

标签: html dom-events

Problem:
I'm not sure whether it is technically better to bind generic events to inner or outer tags. Also concerns deeper nested tags.

Aspects:
Does either use less CPU? Does either have side effects? Does either trigger more or less delayed? Inheritance? this?

What I/we already found out:

  • onclick on <a /> does trigger right before following the link
  • onload does only get triggered by a few tags which really load and display (works on <img />, not on <a />)

Variant example A:

<a href="#" onclick="function();">
  <img src="picture.jpg" />
</a>

Variant example B:

<a href="#">
  <img src="picture.jpg" onclick="function();" />
</a>

The following is rather unrelated but an explanation has been demanded in the comments:

"whats the point of having an <a> tag surrounding the image if you are binding the onclick to the <img> tag?" - @Trug

The point is SEO friendly links with the ability to sidechain effects like an exit modal with a warning, an exit transition animation, an analytics event, or just as a kind of destructor.

Example:

<a href="http://seo.friendly.url/deeplink.htm" 
   onclick="triggerSpecialAnalyticsForExample(); triggerExitModal();">link</a>

1 个答案:

答案 0 :(得分:2)

简单 - 变量B每周一天,2月29日4次。为什么?简单 - 锚元素不支持加载事件,因此等待它将花费非常很长时间。

使用.addEventListener是一种更好的方法,可以出于各种原因将处理程序附加到元素。