从Javascript(DRY)中删除重复的部分

时间:2017-07-18 12:07:04

标签: javascript

我有以下javascript切换不同的视图。一切正常但是它非常重复。我想清理它但不确定我会怎么做。

function switchView () {

var viewContainer = document.getElementById('content-wrapper');
var tileBtn       = document.getElementById('tile-btn');
var listBtn       = document.getElementById('list-btn');
var swipeBtn      = document.getElementById('swipe-btn');


tileBtn.addEventListener( 'click', function(e){

if (viewContainer.classList.contains('list-view') || 
  viewContainer.classList.contains('swipe-view') ) {
   e.preventDefault();
  viewContainer.classList.remove('list-view');
  viewContainer.classList.remove('swipe-view');
  viewContainer.classList.add('tile-view');
}
});

listBtn.addEventListener( 'click', function(e){

if (viewContainer.classList.contains('tile-view') || 
 viewContainer.classList.contains('swipe-view') ) {
   e.preventDefault();
    viewContainer.classList.remove('tile-view');
    viewContainer.classList.remove('swipe-view');
    viewContainer.classList.add('list-view');
}
});

swipeBtn.addEventListener( 'click', function(e){

if (viewContainer.classList.contains('list-view') || 
viewContainer.classList.contains('tile-view') ) {
   e.preventDefault();
    viewContainer.classList.remove('list-view');
    viewContainer.classList.remove('tile-view');
    viewContainer.classList.add('swipe-view');
}
});

};

switchView();

0 个答案:

没有答案