Как минимизировать мой повторяющийся текст и заменить его кодом - PullRequest
0 голосов
/ 22 декабря 2018

Как мне минимизировать мой код jQuery , так как он очень повторяющийся, и я уверен, что он не должен быть таким длинным.

Код работает точночто мне нужно сделать, мне просто нужно минимизировать, чтобы он выглядел чистым и использовать меньше строк кода.

Любое руководство очень ценится и помогает в моем обучении.

Я придумал этот код, чтобы ответить на мой предыдущий вопрос .Так что я учусь благодаря людям на этом сайте.Мне просто нужно немного подтолкнуть в правильном направлении время от времени.:-)

$('#hidden-shoe-sizes').contents().prependTo('.swatches-select');


var sizefour = $('[data-value="4"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizefour) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="4"]'));
  };
});
var sizefive = $('[data-value="5"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizefive) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="5"]'));
  };
});
var sizefivehalf = $('[data-value="5 ½"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizefivehalf) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="5 ½"]'));
  };
});
var sizesix = $('[data-value="6"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizesix) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="6"]'));
  };
});
var sizesixhalf = $('[data-value="6 ½"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizesixhalf) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="6 ½"]'));
  };
});
var sizeseven = $('[data-value="7"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizeseven) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="7"]'));
  };
});
var sizesevenhalf = $('[data-value="7 ½"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizesevenhalf) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="7 ½"]'));
  };
});
var sizeeight = $('[data-value="8"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizeeight) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="8"]'));
  };
});
var sizeeighthalf = $('[data-value="8 ½"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizeeighthalf) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="8 ½"]'));
  };
});
var sizenine = $('[data-value="9"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizenine) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="9"]'));
  };
});
var sizeten = $('[data-value="10"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizeten) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="10"]'));
  };
});
var sizeeleven = $('[data-value="11"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizeeleven) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="11"]'));
  };
});
var sizetwelve = $('[data-value="12"] span').text();
$('.swatch-disabled .basel-tooltip-label').each(function() {
  if ($(this).text() == sizetwelve) {
    $(this).closest('.swatch-disabled').replaceWith($('[data-value="12"]'));
  };
});
.basel-tooltip-label {
  display: none;
}

.swatch-size-large {
  padding: 10px 10px;
  border: 1px solid #ccc;
  float: left;
  margin-right: 4px;
}

.swatch-size-large.swatch-enabled {
  border-color: green;
  background: green;
  color: white;
}

.blue {
  background: blue !important;
}

.orange {
  background: orange !important;
}


/* Hidden Sizes  */

#hidden-shoe-sizes {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total">

  <div class="swatches-select" data-id="pa_size">
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-enabled" data-value="6 ½" style="">
      <span class="basel-tooltip-label">6 ½</span>6 ½
    </div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-enabled" data-value="11" style="">
      <span class="basel-tooltip-label">11</span>11
    </div>
  </div>

  <div id="hidden-shoe-sizes">
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">4</span>4</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">5</span>5</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">5 ½</span>5 ½</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">6</span>6</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">6 ½</span>6 ½</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">7</span>7</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">7 ½</span>7 ½</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">8</span>8</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">8 ½</span>8 ½</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">9</span>9</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">10</span>10</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">11</span>11</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">12</span>12</div>
  </div>
</div>

Спасибо миллион!

Ответы [ 3 ]

0 голосов
/ 22 декабря 2018

Я сжал ваш код JavaScript до этого!

$('#hidden-shoe-sizes').contents().prependTo('.swatches-select');

var sizes = {
    "sizefour": '[data-value="4"]',
    "sizefive": '[data-value="5"]',
    "sizefivehalf": '[data-value="5 ½"]',
    "sizesix": '[data-value="6"]',
    "sizesixhalf": '[data-value="6 ½"]',
    "sizeseven": '[data-value="7"]',
    "sizesevenhalf": '[data-value="7 ½"]',
    "sizeeight": '[data-value="8"]',
    "sizeeighthalf": '[data-value="8 ½"]',
    "sizenine": '[data-value="9"]',
    "sizeten": '[data-value="10"]',
    "sizeeleven": '[data-value="11"]',
    "sizetwelve": '[data-value="12"]'
};

$('.swatch-disabled .basel-tooltip-label').each(function() {
    if ($(this).text() in sizes) {
        $(this).closest('.swatch-disabled').replaceWith($(sizes[$(this.text())]));
    };
});

Надеюсь, это поможет!

0 голосов
/ 22 декабря 2018

Вы можете просто использовать .each(), чтобы просмотреть все [data-value] и .filter(), чтобы получить единицу, равную тексту

$('#hidden-shoe-sizes').contents().prependTo('.swatches-select');

$('[data-value]').each(function(){            // loop through all element has a [data-value] attribute
  var ThisEl = $(this);                       // this element
  var ThisSize = ThisEl.find('span').text();  // get span text
  $('.swatch-disabled .basel-tooltip-label').filter(function(){   // filter if this text == ThisSize
     return $(this).text() == ThisSize;
  }).closest('.swatch-disabled').replaceWith(ThisEl);  // replace with this element
});
.basel-tooltip-label { display: none; }
.swatch-size-large { 
  padding: 10px 10px; 
  border: 1px solid #ccc;
  float: left;
  margin-right:4px;
}
.swatch-size-large.swatch-enabled { 
  border-color: green; 
  background: green;
  color: white;
}
.blue { background: blue !important; }
.orange { background: orange !important; }

/* Hidden Sizes  */
#hidden-shoe-sizes { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total">

<div class="swatches-select" data-id="pa_size">
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-enabled" data-value="6 ½" style="">
    <span class="basel-tooltip-label">6 ½</span>6 ½
  </div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-enabled" data-value="11" style="">
    <span class="basel-tooltip-label">11</span>11
  </div>
</div>

<div id="hidden-shoe-sizes">
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">4</span>4</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">5</span>5</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">5 ½</span>5 ½</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">6</span>6</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">6 ½</span>6 ½</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">7</span>7</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">7 ½</span>7 ½</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">8</span>8</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">8 ½</span>8 ½</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">9</span>9</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">10</span>10</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">11</span>11</div>
  <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">12</span>12</div>
</div>
</div>
0 голосов
/ 22 декабря 2018

Обратите внимание, что "minify" обычно относится к автоматическому процессу сжатия кода перед его передачей по проводам, например замене «var someLongVariableNameHere» на var c.Уверен, что вы ищете, как сделать ваш код более «СУХИМ» («Не повторяйте себя»).

Вместо этого вы можете использовать массив dataValues, сопоставить их с массивомих связанных div s и содержащего текст, затем итерируйте по $('.swatch-disabled .basel-tooltip-label') s один раз , проверьте индекс текста этого элемента в приведенном выше массиве и затем вызовите replaceWith, еслииндекс не -1. ​​

Элементы и тексты заранее извлекаются в массивы, чтобы минимизировать сложность вычислений, которая не является необходимой , но это хорошая вещь, к которой нужно стремитьсядаже если это происходит за счет еще нескольких символов кода.(можно сделать еще лучше, если использовать Map вместо indexOf, если хотите)

$('#hidden-shoe-sizes').contents().prependTo('.swatches-select');
// while the following array declaration *could* be made a bit more DRY
// I think the code is clearest if all the options are listed out like this
const dataValues = [
  '4',
  '5',
  '5 ½',
  '6',
  '6 ½',
  '7',
  '7 ½',
  '8',
  '8 ½',
  '9',
  '10',
  '11',
  '12'
];
const elms = dataValues.map(value => $(`[data-value="${value}"]`));
const texts = elms.map(elm => elm.find('span').text());
$('.swatch-disabled .basel-tooltip-label').each(function() {
  const $this = $(this);
  const i = texts.indexOf($this.text());
  if (i !== -1) {
    $this.closest('.swatch-disabled').replaceWith(elms[i]);
  }
});
.basel-tooltip-label {
  display: none;
}

.swatch-size-large {
  padding: 10px 10px;
  border: 1px solid #ccc;
  float: left;
  margin-right: 4px;
}

.swatch-size-large.swatch-enabled {
  border-color: green;
  background: green;
  color: white;
}

.blue {
  background: blue !important;
}

.orange {
  background: orange !important;
}


/* Hidden Sizes  */

#hidden-shoe-sizes {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total">

  <div class="swatches-select" data-id="pa_size">
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-enabled" data-value="6 ½" style="">
      <span class="basel-tooltip-label">6 ½</span>6 ½
    </div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-enabled" data-value="11" style="">
      <span class="basel-tooltip-label">11</span>11
    </div>
  </div>

  <div id="hidden-shoe-sizes">
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">4</span>4</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">5</span>5</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">5 ½</span>5 ½</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">6</span>6</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">6 ½</span>6 ½</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">7</span>7</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">7 ½</span>7 ½</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">8</span>8</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">8 ½</span>8 ½</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">9</span>9</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">10</span>10</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">11</span>11</div>
    <div class="basel-swatch basel-tooltip  text-only swatch-size-large swatch-disabled"><span class="basel-tooltip-label">12</span>12</div>
  </div>
</div>
...