簡體   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