[英]Event delegation on SVG Elements
I am trying to have a common click handler for all the elements I am appending to a SVG canvas. 我正在尝试为我附加到SVG画布的所有元素设置一个公共点击处理程序。 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'));
});
Update: On the jQuery manual of .on()
it is mentioned that 更新:在.on()
的jQuery手册中提到了
Note: Delegated events do not work for SVG. 注意:委派事件不适用于SVG。
So now the question is any other workaround for this problem? 所以现在问题是这个问题的任何其他解决方法?
When jQuery fails with SVG you can use vanilla js. 当jQuery失败并使用SVG时,您可以使用vanilla js。 Fortunately every browser that supports svg also supports event listeners. 幸运的是,每个支持svg的浏览器也支持事件监听器。 The pure js delegated event is not so ugly: 纯js委托事件并不那么难看:
$("#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. 但您也可以创建自己的功能,以更干净地委派您的活动。
TL/DR: Attach the event listener to a non-SVG parent element. TL / DR:将事件侦听器附加到非SVG父元素。
The note in the jQuery docs is somewhat misleading. jQuery文档中的注释有些误导。
Delegated events do not work for SVG. 委派事件不适用于SVG。
It should probably be... 应该是......
Delegated events do not work when the listener is attached to SVG. 当侦听器附加到 SVG 时,委派事件不起作用。
jQuery's event delegation does not work when the event listener is attached to an SVG element; 当事件监听器附加到SVG元素时,jQuery的事件委托不起作用; however, if you instead attach the listener to a non-SVG parent of the SVG, event propagation works as expected and any selectors that match SVG elements will indeed trigger your event handler function. 但是,如果您将侦听器附加到SVG的非SVG父级,则事件传播按预期工作,并且任何与SVG元素匹配的选择器都将触发您的事件处理函数。
Attaching the listener to the SVG element will not work: 装上监听到SVG元素将无法工作:
$("#floor").on('click','.drawnLine', function() {
console.log($(this).data('index'));
});
But attaching it to a parent element will work: 但是将它附加到父元素将起作用:
$(document.body).on('click','#floor .drawnLine', function() {
console.log($(this).data('index'));
});
Note: one quirk I've noticed is that if the event target is an SVG element, the event won't bubble up all the way to document.body
on iOS. 注意:我注意到的一个怪癖是,如果事件目标是SVG元素,则事件不会一直冒泡到iOS上的document.body
。 So if you want iOS users to be able to trigger your handler function you'll need to attach your event listener to some element in between (such as the div
element your SVG resides in). 因此,如果您希望iOS用户能够触发您的处理程序功能,您需要将事件侦听器附加到其间的某个元素(例如SVG所在的div
元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.