将自定义属性添加到SVG吗?

问题描述 投票:0回答:1

我已经尝试过多种形式的操作,但是我没有使它起作用。我想知道是否可以将自定义属性设置为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

任何线索?

javascript svg setattribute
1个回答
1
投票

使用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>
© www.soinside.com 2019 - 2024. All rights reserved.