如何使这个脚本'防弹'

时间:2017-05-18 19:32:42

标签: javascript jquery demandware

我有一个在调用'box-tip'[0]索引时失败的脚本。有没有办法改善/修复这个脚本或使其更加防弹,以便它不会破坏?欢迎所有建议,请查看下面的代码。

var map = {};

var site = util.getCookie('CTCountry').toLowerCase();
if (site === 'gb' || site === 'us' || site === 'xbr' || site === 'eu') {
  map = {
    '14.5': 33,
    '15': 33,
    '15.5': 34,
    '16': 35,
    '16.5': 35,
    '17': 35,
    '17.5': 36,
    '18': 36,
    '19': 37,
    '20': 37
  };
} else {
  map = {
    '37': 84,
    '38': 84,
    '39': 86,
    '41': 86,
    '42': 89,
    '43': 89,
    '44': 91,
    '46': 91,
    '48': 94,
    '50': 94
  };
}

function applyRecommendedSleeveLength(selectedVal) {
  if (selectedVal !== undefined) {
    var recommendedVal = map[selectedVal.trim()];
    var selected = $('.attribute__swatch--selected:first div').text().trim();
    if (recommendedVal === null || recommendedVal === undefined) {
      selectedVal = $('.attribute__swatch--selected:first div').text().trim();
      recommendedVal = map[selectedVal.trim()];
    }
    var sleevSwatches = document.querySelectorAll('[class*="attribute__swatch--length-"] div');
    sleevSwatches.forEach(function(swatch, i) {
      $('showBorder').removeClass('info');
      swatch.classList.remove('showBorder');
      $('.box-tip').hide();
    });

    if (selected === null || selected === '' || selected === undefined) return;

    var recommendedLis = document.querySelectorAll('[class*="attribute__swatch--length-' + recommendedVal + '"] div');
    recommendedLis.forEach(function(recommendedLi, i) {
      if (recommendedLi !== null && recommendedLi !== undefined) {
        recommendedLi.classList.add('showBorder');
        $('.box-tip').show();
        var currentPosition = $('.showBorder').parent().position().left;
        var info = document.getElementsByClassName('box-tip')[0];
        if (info !== null && info !== undefined) {
          info.style.paddingLeft = currentPosition + -75 + 'px';
        }
      }
    });
  }
}

(function() {
  if (typeof NodeList.prototype.forEach === "function") return false;
  NodeList.prototype.forEach = Array.prototype.forEach;
})();

1 个答案:

答案 0 :(得分:1)

特别针对方框提示:

var info = document.getElementsByClassName('box-tip')[0];

如果没有class='box-tip'的元素,这将会中断,因为你强迫它读取该集合的第一个元素,即使可能没有。这可以很快修复为:

var collection = document.getElementsByClassName('box-tip');
var info = collection.length ? collection[0] : false;
// if there were no elements in the collection info = false;

if (info) {
  info.style.paddingLeft = currentPosition + -75 + 'px' ;
}