开发者

Manipulating classes with jquery

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.


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;
     });
...


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 );
         // ...
     }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜