我有一个应用程序,当用户点击分配给btnAlternativeService的表时,此表中的内容与另一个表交换。
我使用的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);
});
这看起来很漫长 - 我有更好的方式来交换内容吗?
答案 0 :(得分: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;
});
答案 1 :(得分: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')
});