Remove class not working with MooTools

2019-07-16 06:24发布

问题:

I'm using the following piece of code in my webpage to change the class of select elements depending on the choice of a radio button.

The part where I add the class works fine but the other (where I remove them) doesn't work. I get no error in the Error console and when I changed my code to have the part that removes the class put another class to the select elements it worked fine.

<script type="text/javascript">
  window.addEvent('domready', function(){
   $('votconj').addEvent('click', function() {
     // This works fine
     $('first_name_conjoint').addClass("validate['required','nodigit']");
     $('last_name_conjoint').addClass("validate['required','nodigit']");
     $('jj_conjoint').addClass("validate['required']");
     $('mm_conjoint').addClass("validate['required']");
     $('aaaa_conjoint').addClass("validate['required']");
     $('conjoint_regime').addClass("validate['required']");
     new FormCheck('formulaire');
   });

   $('votconj_no').addEvent('click', function() {
     // This doesn't work !
     $('first_name_conjoint').removeClass("validate['required','nodigit']");
     $('last_name_conjoint').removeClass("validate['required','nodigit']");
     $('jj_conjoint').removeClass("validate['required']");
     $('mm_conjoint').removeClass("validate['required']");
     $('aaaa_conjoint').removeClass("validate['required']");
     $('conjoint_regime').removeClass("validate['required']");
     new FormCheck('formulaire');
   });


   new FormCheck('formulaire');
});
</script>


// The radio button
<label>Conjoint :</label>
    <input type="radio" name="votconj" id="votconj" value="oui">oui
    <input type="radio" name="votconj" id="votconj_no" value="non" checked="checked">non

回答1:

It doesn't work because the MooTools ".removeClass()" method simple-mindedly jams the class name into the middle of a regex without bothering to escape embedded regex meta-characters.

You can, however, work around the problem by doing the appropriate quoting yourself. In this example, it'd look like this:

 $('first_name_conjoint').removeClass("validate\\['required','nodigit'\\]");

Here is a jsfiddle.