jQuery添加的svg元素没有显示出来

Cha*_*ing 3 javascript jquery svg

对不起,如果已经回答,我是新来的.

我正在尝试使用jquery创建svg元素,并且我将此代码作为HTML页面的一部分:

<svg viewBox="0 0 1000 500">
    <defs>
        <clipPath id="clip">
            <ellipse cx="100" cy="250" rx="200" ry="50" />
        </clipPath>
    </defs>
    <g>
        <path d="M 0,0 L 1000,0 1000,500 0,500"
            fill="#9ADEFF" />
        <path id="boat" stroke="none" fill="red"
            d="M 100,175 L 300,175 300,325 100,325"
            clip-path="url(#clip)" />
    </g>
    <g id="0002" width="100" height="100%"
        transform="translate(1000)">
        <line x1="50" y1="0" x2="50" y2="300"
            stroke="green" stroke-width="100" />
    </g>
</svg>
Run Code Online (Sandbox Code Playgroud)

和这个Javascript(与jQuery 1.9):

var id = 10000,
    coinArray = []

function generateNextLine(type) {
    $('svg').append($(type()))
    return $('svg')[0]
}

function idNo() {
    id++
    return ((id-1)+"").substr(-4)
}

function random(x,y) {
    if (!y) {
        y=x
        x=0
    }
    x=parseInt(x)
    y=parseInt(y)
    return (Math.floor(Math.random()*(y-x+1))+x)
}

function coins() {
    coinArray[id%10000]=[]
    var gID = idNo(), x,
    g=$(document.createElement('g')).attr({
        id: gID,
        width: "100",
        height: "100%"
    })
    while (3<=random(10)) {
        var randomPos=random(50,450)
        coinArray[(id-1)%10000][x] = randomPos
        $(g).append(
            $(document.createElement('circle'))
            .attr({
                cx: "50",
                cy: randomPos,
                r: "50",
                fill: "yellow"
            })
        )
        x++
    }
    return $(g)[0]
}
Run Code Online (Sandbox Code Playgroud)

当我运行时generateNextLine(coins);,svg添加了这个元素:

<g id="0000" width="100" height="100%">
    <circle cx="50" cy="90" r="50" fill="yellow"></circle>
</g>
Run Code Online (Sandbox Code Playgroud)

但是,svg的实际显示不会改变.如果我将此代码直接添加到svg,它会像我期望的那样呈现,但运行我的javascript函数似乎对显示没有任何作用.我在OS X Lion上使用Chrome 28.

Rob*_*son 6

您必须在SVG命名空间中创建SVG元素,这意味着您无法做到

document.createElement('g')
Run Code Online (Sandbox Code Playgroud)

但相反,你必须写

document.createElementNS('http://www.w3.org/2000/svg', 'g')
Run Code Online (Sandbox Code Playgroud)

圆圈等也一样

  • 实际上,HTML5允许您使用直接嵌入HTML中的`<svg>`元素,而无需命名空间.请参阅[此问题](http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element),了解为什么元素不会显示.**TL; DR**:jQuery的函数专门针对HTML元素定制,其中许多函数对于SVG元素都会失败.例如,jQ使用javascript的`innerHTML`,这对SVG元素不可用. (2认同)