2014-03-04 1 views
0

사이트 사용자가 콘텐츠를 "확대/축소"할 수 있도록 부트 스트랩 그리드 시스템을 사용하는 여러 div가 있습니다. 이 예제에서는 class="abcd b1 col-lg-6" 모두 정상적으로 작동합니다. 하지만 그때 내 b1 클래스의 일부가 .. b10 넘어 가서 내 코드가 더 이상 작동하지 않습니다. 오른쪽에서 왼쪽으로 읽을 수 있도록 코드를 변경하려고했지만 col-lg-6col-lg-10이되면 더 이상 작동하지 않습니다.jQuery에서 문자열 부분을 .slice로 변경하는 방법

그럼 내 질문 : 더 좋은 방법은 .slice 코드 그래서 내 수업 길이가 바뀌어도 작동합니까? "

var otherClasses = $this.attr('class').split(className)[0]; 

이 변수 저장 다른 클래스"ABCD의 B1 '이 아닌 :

<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

대신 .hasClass()를 사용하여 코드를 리팩토링하십시오. 클래스가 특정 순서로 나열된다고 가정하는 것은 신뢰할 수 없습니다. – Blazemonger

+0

감사합니다. 모든 코드를 다시 작성할 필요가 없기를 바랄뿐입니다. 내가 틀렸던 것처럼 보입니다 : p – user3341623

답변

0

나는 :)

먼저 내가 변수를 추가 그것을 해결하는 방법을 발견 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); 
관련 문제