2015-06-07 37 views
0

我不得不CSS類的開始switchfrom-前綴改爲switchto-找到元素的多個類的前綴和前綴切換到所有這些

我得到它的工作,但我現在面臨一個問題,即有在兩個或多個類相同的元素開始與switchfrom-

的問題將是明顯的,當你看我的代碼在這裏: http://jsfiddle.net/9as1ddra/4/

上面的代碼改變switchfrom-div1switchfrom-div2,BU噸不switchfrom-mar

(function($) { 
 
     $.fn.clickToggle = function(func1, func2) { 
 
      var funcs = [func1, func2]; 
 
      this.data('toggleclicked', 0); 
 
      this.click(function() { 
 
       var data = $(this).data(); 
 
       var tc = data.toggleclicked; 
 
       $.proxy(funcs[tc], this)(); 
 
       data.toggleclicked = (tc + 1) % 2; 
 
      }); 
 
      return this; 
 
     }; 
 
    }(jQuery)); 
 
     
 
    $('button#ToggleUI').clickToggle(function() { 
 
     var switchfrom = $('[class^="switchfrom-"]'); 
 
     switchfrom.each(function(index){ 
 
      $(this).attr("class",this.className.replace(/switchfrom-/gi,'switchto-')); 
 
    }); 
 
    }, 
 
    function() { 
 
     var switchto = $('[class^="switchto-"]'); 
 
     switchto.each(function(index){ 
 
      $(this).attr("class",this.className.replace(/switchto-/gi,'switchfrom-')); 
 
     }); 
 
    });
.switchfrom-div1 { 
 
    width:100px; 
 
    height:100px; 
 
    background:#ff0; 
 
    border:1px solid #000; 
 
} 
 
     
 
.switchfrom-div2 { 
 
    width:100px; 
 
    height:100px; 
 
    background:white; 
 
    border:1px solid #000; 
 
} 
 
     
 
.switchto-div1 { 
 
    width:100px; 
 
    height:100px; 
 
    background:green; 
 
    border:1px solid #000; 
 
} 
 
     
 
.switchto-div2 { 
 
    width:100px; 
 
    height:100px; 
 
    background:blue; 
 
    border:1px solid #000; 
 
} 
 

 
.switch-from-mar { 
 
    margin-left:10px; 
 
} 
 

 
.switch-to-mar { 
 
    margin-left:0px; 
 
} 
 
.left { 
 
    float:left; 
 
} 
 
     
 
.right { 
 
    float:right; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<div class="switchfrom-div1 switch-from-mar left"> test1 </div> 
 
<div class="switchfrom-div2 left"> test2 </div> 
 
<br /><br /><br /><br /><br /><br /><br /> 
 
<div class="left"> 
 
    <button id="ToggleUI" style="width:200px;height:50px;">Toggle</button> 
 
</div>

+0

你的代碼中有 「switchfrom-MAR」,而不是 「switchfrom-MAR」。 –

回答

1

$('[class^="switchfrom-"]')由於不靶向.switch-from-mar

您正在尋找與switchfrom開始上課,switch-from-marswitchfrom之間的-

更改您的課程switchfrom-mar它應該工作。或者如果你想保存CSS類,那麼你需要在你的查詢中包含switch-from

JS Fiddle

+0

哎呀!愚蠢的錯誤。對不起! – user1405855