我在那裏三個圓圈繪製一個SVG文件:呼叫SVG javascript函數裏面的html javascript函數
<?xml version="1.0"?>
<svg width="450" height="80" xmlns="http://www.w3.org/2000/svg">
<script>
document.fillCircle = function(id) {
var circles = document.getElementsByTagName('circle'),
circle = document.getElementById(id);
[].forEach.call(circles, function(circle) {
circle.setAttribute('fill','#ffffff');
});
circle.setAttribute('fill', '#000000');
}
</script>
<g>
<line y1="35" x1="35" y2="35" x2="375" stroke-width="3" stroke="#000000"/>
<circle id="state1" r="30" cy="35" cx="35" stroke-width="3" stroke="#000000" fill="#ffffff" onclick="fillCircle(this.id);"/>
<circle id="state2" r="30" cy="35" cx="205" stroke-width="3" stroke="#000000" fill="#ffffff" onclick="fillCircle(this.id);"/>
<circle id="state3" r="30" cy="35" cx="375" stroke-width="3" stroke="#000000" fill="#ffffff" onclick="fillCircle(this.id);"/>
</g>
</svg>
出於測試目的,我有onclick=""
方法,但實際上這個文件是我的HTML文檔中的對象:
<object id="test" data="test-vector.svg" width="100px" height="100px"></object>
我有一個數據集,這三個點表示每個項目的「進步」。我定期通過從服務器拉出新列表來更新JSON集。對於每個項目更改,我想更新實心圓。
我想更新基於一些JavaScript的svg。但是,我無法讓它進入SVG的DOM。我不在乎fillCircle()
是否在svg內,如果我必須使用<embed>
,<object>
或其他東西,但是這種javascript對我不起作用。
<html>
<body>
<object id="test" data="test-vector.svg"></object>
<script>
var svg = document.getElementById('test');
console.log(svg);
svg.fillCircle('state2');
</script>
</body>
</html>
我試過幾件事情我上找到因此,像this one和this one,但無論我考,例外總是:
Uncaught TypeError: Object #<HTMLObjectElement> has no method 'fillCircle'
很明顯我沒有想到對象的負載。感謝您的信息。我不喜歡'onload ='f()'作爲個人偏好的問題,但是你指出了我的正確方向!快速回答的榮譽! –
@robert從一點實驗看來,這似乎不起作用如果SVG的腳本被導入並且沒有嵌入,也就是說fillCircle在SVG導入的外部js文件中,那麼這是預期的行爲還是有另外一種方法? –
@DavidSmith你應該另外提一個關於它的問題 –