我有几个使用bootstrap网格系统的div,允许网站用户“缩放”内容。
在此示例中,class="abcd b1 col-lg-6"
一切正常。
但是后来我有b1
部分类......它会超过b10
,这使我的代码不再有效。
我试图更改代码,以便从右到左阅读...但是当col-lg-6
变为col-lg-10
时,它也不再有效。
所以我的问题是:有没有更好的方法来解决代码问题,这样即使我的课程长度发生变化也能正常工作?
<div id="col" class="abcd b1 col-lg-6"> //the div
<div class="tn bg1">
<div class="ca">
<div class="bp">
<button type="button" id="plus" class="btn" data-toggle="tooltip" data-placement="left" title="Bigger Size"></button> //the button
<button type="button" id="minus" class="btn" data-toggle="tooltip" data-placement="left" title="Smaller Size"></button>
</div>
</div><!--ca-->
</div><!--tn-->
</div><!--col-->
<!--Plus Button-->
var className = ('col-lg-'); //make className = "col-lg-"
$('button#plus').click(function() { //find button#plus and add clickfunction on it.
$this = $(this).closest('div#col'); //find the div that shall change on click, closest div with id=col
var counter = $this.attr('class').split(className)[1]; //get the last section of the class. class "col-lg-6" will set the counter to = 6
var classList = $($this).attr('class').split(/\s+/); //get all the classes of that div, in an objekt array stored in "classList3"
var classString = classList.toString(); //make that objekt array into a string. classstring = "abcd,b1,col-lg-6"
var oldClass = classString.slice(8); //slice out the part i want. oldClass = "col-lg-6"
var nextNum = 1;
if (counter != '') //if the counter has already started
nextNum = parseInt(counter) + 2; //add +2 on click
if (counter < 12) { //if counter are less then 12
$this.removeClass(oldClass).addClass(className + nextNum); //Remove class "col-lg-6" (or what ever the number are at the moment)
}
else { //if counter are bigger or = 12
//do nothing
}
})
答案 0 :(得分:0)
我找到了解决问题的方法:)
首先我添加变量:
var otherClasses = $this.attr('class').split(className)[0];
此变量存储其他类“abcd b1”,而不是“col-lg-6”
然后我改变了这个:
$this.removeClass(oldClass).addClass(className + nextNum);
对此:
$this.removeClass().addClass(otherClasses + className + nextNum);
这将删除所有类,然后添加旧的+新的类。
然后完全删除它,不再需要它了。
var classList = $($this).attr('class').split(/\s+/);
var classString = classList.toString();
var oldClass = classString.slice(8);