SVG Elements上的事件委派 [英] Event delegation on SVG Elements

查看:109
本文介绍了SVG Elements上的事件委派的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我附加到SVG画布的所有元素设置一个公共点击处理程序。但我无法将处理程序委托给新创建的元素。

I am trying to have a common click handler for all the elements I am appending to a SVG canvas. But I cannot delegate the handler to the newly created elements.

这是我试图委托的代码,但没有运气

This is the code I have tried to delegate, but no luck

$("#floor").on('click','.drawnLine', function() {
    //#floor is the SVG Element
    //.drawnLine is the <line> element that is added dynamically
    console.log($(this).data('index'));
});

更新:
关于 .on() 提到


注意:委派事件不适用于SVG。

Note: Delegated events do not work for SVG.

所以现在问题是这个问题的其他任何解决方法吗?

So now the question is any other workaround for this problem?

推荐答案

当jQuery失败并使用SVG时你可以使用vanilla js 。幸运的是,每个支持svg的浏览器也支持事件监听器。纯js委托事件并不那么难看:

When jQuery fails with SVG you can use vanilla js. Fortunately every browser that supports svg also supports event listeners. The pure js delegated event is not so ugly:

$("#floor")[0].addEventListener('click', function(e) {
  // do nothing if the target does not have the class drawnLine
  if (!e.target.classList.contains("drawnLine")) return;
  console.log($(this).data('index'));
});

但您也可以创建自己的功能,以更干净地委派您的活动。

But you can also create your own function to delegate your events more cleanly.

这篇关于SVG Elements上的事件委派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆