如何缩短这种类型的js代码

时间:2017-07-01 06:07:23

标签: javascript jquery

我想在保持功能的同时最小化下面的代码。 请建议我可以用于此类问题的模式。

    // tb bid pickup location picker.
$('#--tb-bid-pickup-location').on('keyup', function () {
    toggler.toggler('#--tb-bid-location-picker', 'pulse');
});

// tb bid drop location picker.
$('#--tb-bid-destination-location').on('keyup', function () {
    toggler.toggler('#--tb-bid-location-picker', 'pulse');
});

// tb bid drop location picker.
$('#--tb-bid-vehicle-type').on('keyup', function () {
    toggler.toggler('#--tb-bid-truck-picker', 'pulse');
});

1 个答案:

答案 0 :(得分:0)

如何创建“等同物”?

要点击的受影响的2列字符串。

var equiv = {
  "--tb-bid-pickup-location"      : "--tb-bid-location-picker",
  "--tb-bid-destination-location" : "--tb-bid-location-picker",
  "--tb-bid-vehicle-type"         : "--tb-bid-truck-picker"
};

$( "[id^='--tb-bid']" ).on('keyup', function () {

  // Get the clicked ID.
  var thisID = $(this).attr("id");

  // If that id exist in the equiv object.
  if( equiv.hasOwnProperty(thisID) ){
    toggler.toggler("#"+equiv[thisID], 'pulse');
  }
});