我已经尝试了几种形式,但我没有让它发挥作用。我想知道是否有一种方法可以为 SVG 元素设置自定义属性。我的代码:
var svgns = "http://www.w3.org/2000/svg";
var rect = document.createElementNS(svgns,'rect');
rect.setAttributeNS(null, 'x', 0);
rect.setAttributeNS(null, 'y', 0);
rect.setAttributeNS(null, 'height', 20);
rect.setAttributeNS(null, 'width', 20);
rect.setAttributeNS(null, 'fill', 'blue');
rect.setAttributeNS(null, 'id', '999');
// my attempt here
rect.setAttributeNS(null, 'foo', 'bar');
rect.addEventListener('click',
function() {
alert(this.foo);
}
,false);
document.getElementById('yard').appendChild(rect);
因此,当我单击该矩形时,它应该(根据我的猜测)提醒属性“foo”的值。相反,它只是输出未定义。
有什么线索吗?
最佳答案
使用this.getAttribute('foo')
。
var svgns = "http://www.w3.org/2000/svg";
var rect = document.createElementNS(svgns, 'rect');
rect.setAttributeNS(null, 'x', 0);
rect.setAttributeNS(null, 'y', 0);
rect.setAttributeNS(null, 'height', 20);
rect.setAttributeNS(null, 'width', 20);
rect.setAttributeNS(null, 'fill', 'blue');
rect.setAttributeNS(null, 'id', '999');
// my attempt here
rect.setAttributeNS(null, 'foo', 'bar');
rect.addEventListener('click',
function() {
alert(this.getAttribute('foo'));
}, false);
document.getElementById('yard').appendChild(rect);
<svg id="yard"></svg>
关于javascript - 向 SVG 添加自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60851340/