javascript - 在每个循环中使用 setAttributeNS

标签 javascript jquery svg

我需要更改我页面上所有 svg 的 url。我有以下代码,但是当我尝试使用 setAttributeNS 时出现错误。

jQuery("[*|href*='icons.svg']:not([href])").each(function () {

  hashedIconUrl = jQuery(this).attr('xlink:href').replace('icons.svg', hashedIcon);
  console.log(hashedIconUrl);

  jQuery(this).setAttributeNS('http://www.w3.org/1999/xlink', 'href', hashedIconUrl);
});

最佳答案

你需要从jQuery对象转换为原生DOM对象来调用setAttributeNS。通常的方法是通过 [0]

jQuery("[*|href*='icons.svg']:not([href])").each(function () {

  hashedIconUrl = jQuery(this).attr('xlink:href').replace('icons.svg', hashedIcon);
  console.log(hashedIconUrl);

  jQuery(this)[0].setAttributeNS('http://www.w3.org/1999/xlink', 'href', hashedIconUrl);
});

关于javascript - 在每个循环中使用 setAttributeNS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001796/

相关文章:

javascript - JS循环向前运行,到达末尾然后无限地向后和向前运行

javascript - 将两个多维数组合并为一个包含对象的多维数组

javascript - 向上滑动一个水平分割网页的 "fixed height div"?

javascript - 自定义wordpress静态主页

java - 使用将 Java 呈现为 String 的 Javascript 获取最终 HTML

javascript - 从 JavaScript 中的数组中提取最重复的值(使用 jQuery)

jquery - History.js 使用 ie6/ie7 恢复状态

jquery - 元素中 .addClass() 方法的问题

javascript - 如何禁用页面加载?

javascript - 如何从 SVGSVGElement 创建 SVGPathElement