2015-04-20 76 views
1

我有一個應用程序,當用戶點擊一個表,分配給btnAlternativeService時,該表中的內容與另一個表交換。使用jquery來回切換內容

我用過的jQuery涉及到爲表中的每段內容創建兩個變量,一個用作JS選擇器,另一個用來保留原始內容。它看起來像這樣:

// Switch between the two services 
    btnAlternativeService.on('click', function(){ 

    // Set original recommended text variables 
    var serviceSubTextOriginal = $('.js-second-step .subtext-top').text(); 
    var serviceProductTitleOriginal = $('.js-second-step .product-title').text(); 
    var serviceMileageOriginal = $('.js-miles').text(); 
    var serviceRecommendationOriginal = $('.js-second-step .full-rec').text(); 

    // Set recommended text selector variables 
    var serviceSubText = $('.js-second-step .subtext-top'); 
    var serviceProductTitle = $('.js-second-step .product-title'); 
    var serviceMileage = $('.js-miles'); 
    var serviceRecommendation = $('.js-second-step .full-rec'); 

    // Set original alternative variables 
    var alternativeProductTitleOriginal = $('.js-alternative h3').text(); 
    var alterativeMilageOriginal = $('.js-miles-alternative').text(); 
    var alternativeSubTextOriginal = $('.js-alternative .alternative-subtext').text(); 

    // Set alternative selector variables 
    var alternativeProductTitle = $('.js-alternative h3'); 
    var alterativeMilage = $('.js-miles-alternative'); 
    var alternativeSubText = $('.js-alternative .alternative-subtext'); 

    // Swap everything around 
    serviceProductTitle.text(alternativeProductTitleOriginal); 
    serviceMileage.text(alterativeMilageOriginal); 
    serviceRecommendation.text(alternativeSubTextOriginal); 
    alternativeSubText.text(serviceRecommendationOriginal); 
    alternativeProductTitle.text(serviceProductTitleOriginal); 
    alterativeMilage.text(serviceMileageOriginal); 
    }); 

這似乎很漫長 - 有沒有更好的方式來交換內容?

+5

提琴會好打轉轉爲了我們!!! –

+1

在我看來,代碼太多,命名不佳,需要2個對象,一個用於選擇器,另一個用於原始內容和功能,需要2個參數(2個對象)。該函數然後將交換對象proeprties。 –

回答

3

您可以選擇按訂單的元素,創建2個收藏和使用指標的設置文本內容:

var $first = $('.js-second-step .subtext-top, ...'); 
var $second = $('.js-alternative h3, ...'); 

$first.text(function(index, thisText) { 
    // select the corresponding element from the second set 
    var $that = $second.eq(index), thatText = $that.text(); 

    $that.text(thisText); 
    return thatText; 
}); 
0

使用功能:

function switchContent(selector_1, selector_2){ 
    data_1 = $(selector_1).text() 
    data_2 = $(selector_1).text() 
    $(selector_1).text(data_2) 
    $(selector_2).text(data_1) 
} 

btnAlternativeService.on('click', function(){ 
    switchContent('.js-alternative h3', '.js-second-step .product-title') 
    switchContent('.js-miles-alternative', '.js-miles')  
    switchContent('.js-alternative .alternative-subtext', '.js-second-step .full-rec') 
});