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

时间:2015-01-24 15:30:00

标签: javascript

在我工作的网页上,我有很多小图片,我想分配同一组事件。我没有逐个添加它们,而是认为如果我能让这种类型的元素继承这些事件会更优雅。

我想到的是:

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)我是否不打扰原来的HTMLElement?

b)例如,是否可以命名自定义对象属性    “.onmouseover”就像经典的方式:     originalHTMlementlement.onmouseover = function()......?

c)更概念化:是否可以将自定义对象与HTML混合使用    elemenst / DOM节点?

1 个答案:

答案 0 :(得分:0)

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

我认为迭代目标元素并将事件附加到它们上确实存在问题,但是如果你不喜欢它,你可以使用event delegation



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>
&#13;
&#13;
&#13;

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