简体   繁体   中英

Adding svg element using jquery append

I am trying to create a graph using svg element and then appending a rect element for each bar of the graph in a loop.

How do I pass the "moveBar" variable into the .append statement to adjust the width attribute of the rect element?

 $(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>

You can use Template literals to assign variable value to your rect tag like this:

 $(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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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