Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery中的attr()是否强制使用小写?_Javascript_Jquery_Svg_Attr_Lowercase - Fatal编程技术网

Javascript jQuery中的attr()是否强制使用小写?

Javascript jQuery中的attr()是否强制使用小写?,javascript,jquery,svg,attr,lowercase,Javascript,Jquery,Svg,Attr,Lowercase,我正在尝试操作svg的“viewBox”属性,该属性如下所示: <svg viewBox="0 0 100 200" width="100" ...> ... </svg> 但是,这会在名为“viewbox”的元素中创建一个新属性。请注意小写而不是大小写。是否还有另一个我应该使用的函数?在操作attr之前,是否要确保删除它(如果它已经存在) $("svg").removeAttr("viewBox") 然后重新创建它 $("svg").attr("viewBox","

我正在尝试操作svg的“viewBox”属性,该属性如下所示:

<svg viewBox="0 0 100 200" width="100" ...> ... </svg>

但是,这会在名为“viewbox”的元素中创建一个新属性。请注意小写而不是大小写。是否还有另一个我应该使用的函数?

在操作attr之前,是否要确保删除它(如果它已经存在)

$("svg").removeAttr("viewBox")
然后重新创建它

$("svg").attr("viewBox","...");

我能够使用纯javascript获取元素,并使用

var svg = document.getElementsByTagName("svg")[0];


您可以使用jQuery挂钩:

['preserveAspectRatio', 'viewBox'].forEach(function(k) {
  $.attrHooks[k.toLowerCase()] = {
    set: function(el, value) {
      el.setAttribute(k, value);
      return true;
    },
    get: function(el) {
      return el.getAttribute(k);
    },
  };
});
现在jQuery将使用setter/getter来操作这些属性

注意
el.attr('viewBox',null)
将失败;你的带钩人不会被叫来的。相反,您应该使用el.removeAttr('viewBox')。

Per“XHTML文档必须对所有HTML元素和属性名称使用小写。”

因此,为了避免属性在XHTML文档中转换为小写,您需要使用
document.createElements()
创建指定名称空间的元素,如:

var svg=document.createElements('http://www.w3.org/2000/svg'、'svg');
setAttribute('viewBox','0 512');
如果计划添加
元素,则还需要在创建元素时指定名称空间以及
xlink:href
属性,如:

var use=document.createElements('http://www.w3.org/2000/svg","使用",;
use.setAttributeNS('http://www.w3.org/1999/xlink'、'xlink:href'、'#您的_svg_id');

重复问题,谢谢andres。尝试搜索,但未找到该方法。虽然此方法有效,但无法阻止旧行为的发生。因此,元素将同时具有
viewbox
viewbox
属性。并不是说它不起作用,而是它没有它能被修复的那么干净。setter应返回
true
svg.setAttribute("viewBox","...");
['preserveAspectRatio', 'viewBox'].forEach(function(k) {
  $.attrHooks[k.toLowerCase()] = {
    set: function(el, value) {
      el.setAttribute(k, value);
      return true;
    },
    get: function(el) {
      return el.getAttribute(k);
    },
  };
});