使 HTML 元素从自定义对象继承事件

Make HTML element inherit events from custom object

本文关键字:对象 继承 事件 自定义 HTML 元素      更新时间:2023-09-26

在我正在工作的网页中,我有很多小图像要分配相同的事件集。与其一个接一个地添加它们,我认为如果我能让这种类型的元素继承这些事件会更优雅。

我想到的是这样的:

function InheritEvents(){};
InheritEvents.prototype.onmouseover = function(){...action a..};
InheritEvents.prototype.onmouseout  = function(){...action b..};
var temp = originalHTMLElement.constructor; //(in this case img)
originalHTMLElement.prototype = new InheritEvents();
originalHTMLElement.constructor = temp;

a) 我不是打扰了原来的HTML吗?

b) 是否可以命名自定义对象属性,例如 ".onmouseover"就像经典方式一样: originalHTMLElement.onmouseover = function()... ?

c) 更具概念性:是否可以将自定义对象与 HTML 混合 elemenst/DOM nodes ?

我强烈建议不要这样做。无论如何,它可能都行不通,但一般来说,弄乱主机对象的原型是一个坏主意。

我认为遍历目标元素并将事件附加到它们应该没有问题,但如果你不喜欢这样,你可以使用事件委托:

window.onload = function() {
  document.getElementById("images").onclick = function(e) {
    if (e.target && e.target.classList.contains("clickable")) {
      e.stopPropagation();
      console.log("I've been clicked!");
    }
  }
}
#images div {
  width: 40px;
  height: 40px;
  float: left;
  margin: 5px;
  background-color: blue;
}
#images div.clickable {
  background-color: red;
}
#images + * {
  clear: both;
}
<div>
  <div id="images">
    <!-- Pretend that these DIVs are your images -->
    <div></div>
    <div class="clickable"></div>
    <div></div>
    <div></div>
    <div class="clickable"></div>
  </div>
  <div>
    Click one of the red images above
  </div>
</div>

当然,如果您使用的是 jQuery,.on() 方法可以在一行中处理"将事件处理程序添加到集合的所有成员"选项和事件委托选项。