Manipulating classes with jquery

♀尐吖头ヾ 提交于 2019-12-11 14:05:14

问题


I have a select box with values: apple-80 apple-100 apple-120 apple-300

I have: <body class="fruit apple-120 otherclass anotherclass">

I want to manipulate the body class "apple-120" to get replaced by any of selected value from the select box while keeping the fruit, otherclass, anotherclass, class untouched.

So far I created this:

$.fn.classSwitcher = function(options) {
  var baseOptions = {
    classTarget: 'body',
    oldClass: 'apple-120'
    };

  var options = $.extend(baseOptions, options);

  return this.each(function() {
         $(this).click(function() { 
           var t = $(this);
           var optionVal = t.val();
             $(options.classTarget).removeClass(options.oldClass).addClass(optionVal);
         });
  });
};

Then I have:

$('#sel option').classSwitcher();

This replaced the class, but on the next click of the select box, more select option values are added as new classes, which was not what I wanted.

I just want to replace "apple-120" with a new value, not adding more. Any other click will just replace the same target class.

Plus, I also wanted to grab all select box values to keep them as a condition to narrow down selection on those classes. Says, if a class matches any of the values in the select box, do something.

Any hint would be very much appreciated. Thanks.


回答1:


The problem is that you are not updating options.oldClass so it always tries to remove the original apple-120. You should set it to the class that's being assigned when you update:

...
     $(this).click(function() { 
       var t = $(this);
       var optionVal = t.val();
       $(options.classTarget).removeClass(options.oldClass).addClass(optionVal);
       options.oldClass = optionVal;
     });
...



回答2:


If you want to remember values from previous invocations of click, you could store the value with data()

$(this).click(function() { 
     var val = $(this).val();
     if (val != $(this).data('previous')) {
         $(this).data('previous', val );
         // ...
     }
});


来源:https://stackoverflow.com/questions/2220914/manipulating-classes-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!