[英]want to remove a previously added class and add a new class to the same div
I am making an frombuilder in which on choosing an option value (from 1 to 12) it adds an col-xs-(1-12) class to an div. 我正在制作一个frombuilder,其中在选择一个选项值(从1到12)时,它向div添加了col-xs-(1-12)类。 But when I want to choose an other option to add some different col-xs-(1-12) class previous class doesn't get deleted. 但是,当我想选择其他选项来添加一些不同的col-xs-(1-12)类时,不会删除先前的类。
function addGrid() {
console.log("addGrid Called !");
console.log($(".grid_cols").val());
var col_val = $(".grid_cols").val();
console.log("col_val :" + col_val - 1);
if ($(".fb-field-wrapper").find('col-xs' + '-' + col_val)) {
console.log("hasClass ??");
$(".fb-field-wrapper").removeClass('col-xs' + '-' + col_val);
console.log("removed class");
}
else {
$(".fb-field-wrapper").addClass('col-xs' + '-' + col_val);
}
}
You may also: 您还可以:
col-xs-<num>
exists 使用一点正则表达式查看模式col-xs-<num>
存在 Here is your code, simplified with the above points. 这是您的代码,经过上述几点简化。
function addGrid() {
var col_val = $(".grid_cols").val(),
$wrapper = $(".fb-field-wrapper"),
matches = $wrapper.attr("class").match(/col-xs-(\d+)/i);
//See if class 'col-xs-<num>' exists
if (matches !== null) {
//If yes, remove that class
$wrapper.removeClass("col-xs-" + matches[1]);
}
//Add Class
$wrapper.addClass('col-xs' + '-' + col_val);
}
Note: In your code, $(".fb-field-wrapper").find('col-xs' + '-' + col_val)
would try to find the children of .fb-field-wrapper
with the class col-xs-<num>
whereas you wanted to see if that class exists in the wrapper itself. 注:在你的代码中, $(".fb-field-wrapper").find('col-xs' + '-' + col_val)
将试图找到的孩子.fb-field-wrapper
带班col-xs-<num>
而您想查看包装器本身中是否存在该类。 For that, you'd do: 为此,您可以这样做:
if ( $(".fb-field-wrapper").hasClass('col-xs-' + col_val) ) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.