jQuery SVG, why can't I addClass?

前端 未结 15 1849
失恋的感觉
失恋的感觉 2020-11-22 02:25

I am using jQuery SVG. I can\'t add or remove a class to an object. Anyone know my mistake?

The SVG:



        
相关标签:
15条回答
  • 2020-11-22 02:57

    jQuery does not support the classes of SVG elements. You can get the element directly $(el).get(0) and use classList and add / remove. There is a trick with this too in that the topmost SVG element is actually a normal DOM object and can be used like every other element in jQuery. In my project I created this to take care of what I needed but the documentation provided on the Mozilla Developer Network has a shim that can be used as an alternative.

    example

    function addRemoveClass(jqEl, className, addOrRemove) 
    {
      var classAttr = jqEl.attr('class');
      if (!addOrRemove) {
        classAttr = classAttr.replace(new RegExp('\\s?' + className), '');
        jqEl.attr('class', classAttr);
      } else {
        classAttr = classAttr + (classAttr.length === 0 ? '' : ' ') + className;
        jqEl.attr('class', classAttr);
      }
    }
    

    An alternative all tougher is to use D3.js as your selector engine instead. My projects have charts that are built with it so it's also in my app scope. D3 correctly modifies the class attributes of vanilla DOM elements and SVG elements. Though adding D3 for just this case would likely be overkill.

    d3.select(el).classed('myclass', true);
    
    0 讨论(0)
  • 2020-11-22 03:00

    Or just use old-school DOM methods when JQ has a monkey in the middle somewhere.

    var myElement = $('#my_element')[0];
    var myElClass = myElement.getAttribute('class').split(/\s+/g);
    //splits class into an array based on 1+ white space characters
    
    myElClass.push('new_class');
    
    myElement.setAttribute('class', myElClass.join(' '));
    
    //$(myElement) to return to JQ wrapper-land
    

    Learn the DOM people. Even in 2016's framework-palooza it helps quite regularly. Also, if you ever hear someone compare the DOM to assembly, kick them for me.

    0 讨论(0)
  • 2020-11-22 03:01

    If you have dynamic classes or don't know what classes could be already applied then this method I believe is the best approach:

    // addClass
    $('path').attr('class', function(index, classNames) {
        return classNames + ' class-name';
    });
    
    // removeClass
    $('path').attr('class', function(index, classNames) {
        return classNames.replace('class-name', '');
    });
    
    0 讨论(0)
提交回复
热议问题