javascript - 向 SVG 添加自定义属性?

标签 javascript svg setattribute

我已经尝试了几种形式,但我没有让它发挥作用。我想知道是否有一种方法可以为 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/

相关文章:

javascript - 如何扩展接口(interface)并覆盖属性的类型?

javascript - 确定 SVG 线段的长度、斜率和其他测量值

javascript - 如何只缩放 svg 的一部分

d3.js - 如何在 vue js 方法中捕获 svg 元素悬停事件以及如何将原生 javascript 悬停事件组合到 vue 方法

javascript - 如何使用javascript或jquery修改一个:before psedo-element attribute?

javascript - 表标签在 Chrome/Firefox 中禁用吗?

javascript - 如何在 FireFox 浏览器上隐藏 Powertip 工具提示

javascript - 节点对象树如何进入浏览器

javascript - javascript函数什么时候需要在require语句后添加空括号?

java - 在包含jsp之前设置属性