用jQuery操作类 [英] Manipulating classes with jquery

查看:68
本文介绍了用jQuery操作类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有值的选择框: 苹果80 苹果100 苹果120 苹果300

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

我有:<body class="fruit apple-120 otherclass anotherclass">

我要操纵实体类"apple-120",使其被选择框中的任何选定值替换,同时保持水果,otherclass,anotherclass,class不变.

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

那我有:

$('#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.

我只想用一个新值替换"apple-120",而不要增加更多值.任何其他单击都将替换相同的目标类.

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.

推荐答案

问题是您没有更新options.oldClass,因此它总是尝试删除原始的apple-120.您应该将其设置为更新时分配的类:

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

这篇关于用jQuery操作类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆