将自定义属性添加到 SVG?

Add custom attribute to SVG?

我已经尝试了几种方法,但我没有让它起作用。我想知道是否有一种方法可以将自定义属性设置为 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' 的值。相反,它只是输出 undefined.

有线索吗?

使用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>