gpt4 book ai didi

javascript - 使用 jquery append 添加 svg 元素

转载 作者:行者123 更新时间:2023-12-02 21:32:53 28 4
gpt4 key购买 nike

我正在尝试使用 svg 元素创建一个图形,然后在循环中为图形的每个条形 append 一个 rect 元素。

如何将“moveBar”变量传递到.append语句中以调整矩形元素的宽度属性?

        $(document).ready(function () {
var ulEmployees = $('#ulEmployees');
var moveBar = 0;

$('#btn').click(function () {
$.ajax('api/AnnualPowerInterruptions', {
dataType: 'json',
success: function (data) {
ulEmployees.empty();
$('#graphData2').append("<svg id=mySVG class='chart' width='500' height='500'></div>");
$.each(data, function (index, val) {
var name = val.year;
ulEmployees.append('<li>' + name + '</li>');
$('#mySVG').append("<g transform='translate (100, 0)'><rect width=moveBar 'height='40' style='fill:red'> </rect> <text x='-50' y='30' fill='red'> blue </text></g>");
window.alert(moveBar);
moveBar = moveBar + 50;
});
$("#graphData2").html($("#graphData2").html())
}

});

});
            <div id="graphData2">
</div>

最佳答案

您可以使用Template literals将变量值分配给您的 rect 标记,如下所示:

$(document).ready(function() {
var ulEmployees = $("#ulEmployees");
var moveBar = 0;

$("#btn").click(function() {
$.ajax("api/AnnualPowerInterruptions", {
dataType: "json",
success: function(data) {
ulEmployees.empty();
$("#graphData2").append(
"<svg id=mySVG class='chart' width='500' height='500'></div>"
);
$.each(data, function(index, val) {
var name = val.year;
ulEmployees.append("<li>" + name + "</li>");
$("#mySVG").append(
`<g transform='translate (100, 0)'><rect width=${moveBar} 'height='40' style='fill:red'> </rect> <text x='-50' y='30' fill='red'> blue </text></g>`
);
window.alert(moveBar);
moveBar = moveBar + 50;
});
$("#graphData2").html($("#graphData2").html());
}
});
});
});
<div id="graphData2">
</div>

关于javascript - 使用 jquery append 添加 svg 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60574737/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com