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