我有一个应用程序,当用户单击分配给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);
  });


这似乎很漫长-我是否有更好的方法来交换内容?

最佳答案

您可以按顺序选择元素并创建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;
});

关于javascript - 使用Jquery来回切换内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29747183/

10-10 21:43
查看更多