我正在创建一个<svg>
使用 jQuery,并将其附加到 <div>
。
我可以访问<svg>
通过使用each()
之后append()
,但处理程序不起作用。如果我事先创建它,它就会这样做。
$(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>
关于javascript - 如何使用 jQuery 将事件绑定(bind)到新创建的 SVG 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965412/