Why is jQuery auto lower casing attribute values?

后端 未结 3 651
离开以前
离开以前 2020-12-16 11:04

I am working with an SVG that is directly placed into an HTML file


   Contents...

Using javascript/jQuery I want t

3条回答
  •  遥遥无期
    2020-12-16 11:35

    Because html is case insensitive and xhtml tags and attributes should be lower case, jQuery converts the attribute name to lower case. Because xml is case sensitive, it's an issue for embedded xml language when they use camel case attribute names like SVG does.

    You could use jQuery hooks to handle those attribute names you would like the case to not be converted. If jQuery find jQuery.attrHooks[attributename].set to be set it will use it to set the attribute. Same for jQuery.attrHooks[attributename].get when it tries to retrieve the attribute value. E.g.:

    ['preserveAspectRatio', 'viewBox'].forEach(function(k) {
      $.attrHooks[k.toLowerCase()] = {
        set: function(el, value) {
          el.setAttribute(k, value);
          return true; // return true if it could handle it.
        },
        get: function(el) {
          return el.getAttribute(k);
        },
      };
    });
    

    Now jQuery will use your setter/getters to manipulate those attributes.

    Note: el.attr('viewBox', null) would failed; your hook setter won't be called. Instead you should use el.removeAttr('viewBox').

提交回复
热议问题