【问题标题】:svg+jquery, alert function not working when clicked on the created svgsvg + jquery,单击创建的svg时警报功能不起作用
【发布时间】:2014-06-16 19:20:34
【问题描述】:

此代码在单击组件按钮时动态添加 svg 图像。之后我 尝试将警报功能传递给动态创建的组件,但它不响应单击。请帮忙。我尝试使用 id、class、path 传递函数。

<html>
<head>
<title>buttons</title>
<style>
input[type="button"]{ 
color:#050; 
font: old 84% 'trebuchet ms',helvetica,sans-serif; 
background-color:#fed; 
border:1px solid; 
border-color: #696 #363 #363 #696; 
}
</style>
</head>
<body>
<svg  class="svg-main" style="height:60%;" xmlns="http://www.w3.org/2000/svg"     xlink="http://www.w3.org/1999/xlink">

</svg> 
<input type="button" class="Mouse" value="Cursor"/>
<input type="button" class="Component" value="Resistor"/>
<script src="jquery-1.11.1.js"></script>
<script type="text/javascript" src="d3.v2.js"></script> 
<script type="text/javascript" src="jquery-svgpan.js"></script>
<script>
$(document).ready(function(){

var $svg= $('.svg-main');
$(".Component").click(function(){
$(SVG('path'))
.attr('d','M10 15 l15 0 l2.5 -5 l5 10 l5 -10 l5 10 l5 -10 l5 10 l2.5 -5 l15 0')
.attr('fill', 'none')
.attr('stroke', 'black')
.attr('stroke-width', 2)
.attr('stroke-linejoin' , 'bevel')
.attr('id' , 'res')
.appendTo($svg);

});
$("#res").click(function(){
alert("hi");
});
function SVG(tag)
{
return document.createElementNS('http://www.w3.org/2000/svg',tag);
}
});
</script>
</body>
</html>

【问题讨论】:

    标签: jquery svg


    【解决方案1】:

    #res 在您绑定事件时不存在。

    创建元素后使用event delegation或绑定事件。

    代表:

    $("svg").on("click", "path", function(){ alert("hi"); });
    

    绑定:

    $(SVG("path")).attr(...).on("click", function(){ alert("hi"); }).appendTo($svg);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      相关资源
      最近更新 更多