繁体   English   中英

如何使用jQuery将事件绑定到新创建的SVG元素?

[英]How to bind events to a newly created SVG element using jQuery?

我正在使用jQuery创建一个<svg> ,并将其附加到<div>

我可以在append()之后使用each()访问<svg> ,但处理程序不起作用。 如果我事先创建它,它确实如此。

 $(document).ready(function() { $('#testbtm').click(function() { var svgElement = $('<svg class="hexagon" class="ui-widget-content">\\ <text fill="black" x=75 y=75 style="text-anchor: middle">1</text>\\ <path d="M38 0 L113 0 L150 65 L113 130 L38 130 L0 65 Z" / fill="none" stroke="blue"></svg>'); svgElement.children('text').text(1); svgElement.attr("class", "hexagon ui-widget-content"); $("#display").append(svgElement); }); //end click $('#testbtm2').click(function() { $('.hexagon').each(function() { $(this).children('text').text('hi'); }); }); // end click $('.hexagon').click(function() { $(this).children('path').css('fill', 'blue'); }); //end click }); // end ready 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="display"> <svg class="hexagon" class="ui-widget-content"> <text fill="black" x=75 y=75 style="text-anchor: middle">1</text> <path d="M38 0 L113 0 L150 65 L113 130 L38 130 L0 65 Z" / fill="none" stroke="blue"> </svg> </div> <button id="testbtm">test</button> <button id="testbtm2">test2</button> 

$(selector).click(f); 当前在DOM中的所有元素添加单击处理程序。

因为在您调用jquery的click函数时,通过单击按钮创建的新六边形不在此处,所以它不会获得click处理程序。 您需要为您创建的每个新元素(它是否为SVG)再次执行此操作。

 $(document).ready(function() { function hexagonClick(){ $(this).children('path').css('fill', 'blue'); }; $('#testbtm').click(function() { var svgElement = $('<svg class="hexagon" class="ui-widget-content">\\ <text fill="black" x=75 y=75 style="text-anchor: middle">1</text>\\ <path d="M38 0 L113 0 L150 65 L113 130 L38 130 L0 65 Z" / fill="none" stroke="blue"></svg>'); svgElement.children('text').text(1); svgElement.attr("class", "hexagon ui-widget-content"); $("#display").append(svgElement); // add the onclick handler to the new element. svgElement.click(hexagonClick); }); //end click $('#testbtm2').click(function() { $('.hexagon').each(function() { $(this).children('text').text('hi'); }); }); // end click $('.hexagon').click(hexagonClick); //end click }); // end ready 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="display"> <svg class="hexagon" class="ui-widget-content"> <text fill="black" x=75 y=75 style="text-anchor: middle">1</text> <path d="M38 0 L113 0 L150 65 L113 130 L38 130 L0 65 Z" / fill="none" stroke="blue"> </svg> </div> <button id="testbtm">test</button> <button id="testbtm2">test2</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM