Why is jQuery auto lower casing attribute values?

后端 未结 3 653
离开以前
离开以前 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').

    0 讨论(0)
  • 2020-12-16 11:48

    I might depend on your encoding document type. XHTML documents must use lower case for all HTML element and attribute names. I'm not sure about HTML.

    Update 2

    The only solution I could find is to use:

    $("svg")[0].setAttribute("viewBox", "0 0 166 361");
    

    Update

    I can't explain it for any reason, I tested on my own host because JsFiddle always uses XHTML (boo!). In all cases it was lowercase, but it was still an SVG Element in FF, Chrome and IE9 (I don't know if they were valid because I don't know SVG I'm afraid).

    Firefox Example Chrome Example IE Example

    0 讨论(0)
  • 2020-12-16 12:00

    http://docs.jquery.com/Won't_Fix#SVG.2FXML.2FVML_Bugs

    jQuery recognise that they toLower all attribute names but don't care to make exceptions/remove this line as bugs relating to SVG are ignored (the toLower is superfluous in my opinion).

    0 讨论(0)
提交回复
热议问题