我有一个脚本在调用"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;
})();
专门针对框尖:
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' ;
}