Sta*_*arx 19 javascript jquery svg
我正在尝试为我附加到SVG画布的所有元素设置一个公共点击处理程序.但我无法将处理程序委托给新创建的元素.
这是我试图委托的代码,但没有运气
$("#floor").on('click','.drawnLine', function() {
//#floor is the SVG Element
//.drawnLine is the <line> element that is added dynamically
console.log($(this).data('index'));
});
Run Code Online (Sandbox Code Playgroud)
更新:
在jQuery手册中.on()提到它
注意:委派事件不适用于SVG.
所以现在问题是这个问题的任何其他解决方法?
met*_*ion 13
当jQuery失败并使用SVG时,您可以使用vanilla js.幸运的是,每个支持svg的浏览器也支持事件监听器.纯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'));
});
Run Code Online (Sandbox Code Playgroud)
但您也可以创建自己的功能,以更干净地委派您的活动.
TL/DR:将事件侦听器附加到非SVG父元素.
jQuery文档中的注释有些误导.
委派事件不适用于SVG.
应该是......
当侦听器附加到 SVG 时,委派事件不起作用.
当事件监听器附加到SVG元素时,jQuery的事件委托不起作用; 但是,如果您将侦听器附加到SVG的非SVG父级,则事件传播按预期工作,并且任何与SVG元素匹配的选择器都将触发您的事件处理函数.
装上监听到SVG元素将无法正常工作:
$("#floor").on('click','.drawnLine', function() {
console.log($(this).data('index'));
});
Run Code Online (Sandbox Code Playgroud)
但是将它附加到父元素将起作用:
$(document.body).on('click','#floor .drawnLine', function() {
console.log($(this).data('index'));
});
Run Code Online (Sandbox Code Playgroud)
注意:我注意到的一个怪癖是,如果事件目标是一个SVG元素,那么事件将不会一直冒泡到document.bodyiOS上.因此,如果您希望iOS用户能够触发您的处理程序功能,您需要将事件侦听器附加到其间的某个元素(例如divSVG所在的元素).