使用 jquery 操作类
我有一个带有值的选择框: 苹果80 苹果100 苹果120 apple-300
我有:
我想操作主体类“apple-120”以替换为从选择框,同时保持水果、其他类、另一个类、类不变。
到目前为止,我创建了这个:
$.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();
这替换了该类,但是在下次单击选择框时,更多的选择选项值被添加为新类,这不是我想要的。
我只想用新值替换“apple-120”,而不是添加更多值。任何其他点击都只会替换相同的目标类。
另外,我还想获取所有选择框值,将它们作为缩小这些类选择范围的条件。意思是,如果一个类与选择框中的任何值匹配,则执行某些操作。
任何提示将非常感激。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您没有更新
options.oldClass
,因此它总是尝试删除原始的apple-120
。您应该将其设置为更新时分配的类:The problem is that you are not updating
options.oldClass
so it always tries to remove the originalapple-120
. You should set it to the class that's being assigned when you update:如果您想记住以前调用 click 的值,可以使用 data() 存储该值
If you want to remember values from previous invocations of click, you could store the value with data()