我有一个脚本,我想要更加防弹。目前页面断开,因为找不到类box-tip。为了使这个防弹而不抛出错误,我怎样才能将下面的代码重写为jquery获得与js相同的结果
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()];
}
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 sleeveRecom = document.getElementsByClassName('box-tip');
var info = sleeveRecom.length ? sleeveRecom[0] : false;
info.style.paddingLeft = currentPosition + -75 + 'px';
}
});
} }
答案 0 :(得分:2)
如果要检查div是否存在,可以使用它(使用JQuery):
if ( $('.box-tip').length != 0 ){
//do something
}
或者 - 你已经编辑了你的帖子 - 没有JQuery:
if ( document.getElementsByClassName('box-tip').length != 0 ){
//do something
}
答案 1 :(得分:0)
只需使用jQuery即可。如果该类不存在,则jQuery方法不会导致错误
function applyRecommendedSleeveLength() {
$('.box-tip').show().first().css('paddingLeft', (currentPosition - 75) + 'px');
}