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);
});
這似乎很漫長 - 有沒有更好的方式來交換內容?
提琴會好打轉轉爲了我們!!! –
在我看來,代碼太多,命名不佳,需要2個對象,一個用於選擇器,另一個用於原始內容和功能,需要2個參數(2個對象)。該函數然後將交換對象proeprties。 –