【问题标题】:jquery created svg rect doesn't appearjquery 创建的 svg rect 没有出现
【发布时间】:2014-01-21 20:51:52
【问题描述】:

我正在尝试使用 jQuery 创建一个 SVG 条形图,但没有其他库,但是当我创建矩形时,它们不会显示在浏览器中,尽管在 html 中键入的相同的会显示出来。

var data = [4, 8, 15, 16, 23, 42];
var chart = jQuery("#chart");
jQuery.each(data, function(index, value) {
    var bar = jQuery("<rect/>");
    chart.append(bar);
    bar.attr("y", index * 20)
        .attr("width", value * 10)
        .attr("height", 20);
});

和html:

<svg id="chart" class="chart" width=420 height=120 style="display: block;">
    <rect y="0" width="40" height="20"></rect> <!--added to test-->
</svg>

输入的 rect 标记看起来很好,使用 Chrome 中的开发人员工具,它看起来与我的代码生成的第一个相同,但生成的代码不会显示。

【问题讨论】:

  • 我的回答对你有用吗?
  • 你可以试试我的 jQuery hack:stackoverflow.com/questions/11792754/…
  • 你有没有发现为什么你创建的矩形没有出现?我遇到了同样的问题,js 生成的矩形没有显示,但在元素查看器中看起来与确实出现的手写 rect 元素相同。

标签: jquery svg


【解决方案1】:
$(document).ready(function() {
    var data = [4, 8, 15, 16, 23, 42];
    var chart = jQuery("#chart2");
    jQuery.each(data, function(index, value) {
        var bar = $(document.createElementNS("http://www.w3.org/2000/svg", "rect")).attr({
            x: 0,
            y: index * 20,
            width: value * 10,
            height: 20,
            stroke: "red",
            fill: "white"
        });
        chart.append(bar);
    });
});​

http://jsfiddle.net/26ybf/

编辑:显然你可以删除描边和填充属性,我只是把它放在那里以确保它正常工作。干杯!

【讨论】:

  • 是的!我很怀疑,但显然 jQuery 在没有使用 document.createElementNS 来“真正”创建元素的情况下创建了错误的元素类型。
【解决方案2】:

尝试刷新你的元素:

jQuery.each(data, function(index, value) {
    ...
}    
chart.html(function(){return this.innerHTML});

SEE jsFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 2017-09-10
    • 2017-05-26
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多