开发者问题收集

阻止页面中的 JavaScript 函数

2021-12-01
145

我网站的 JS 文件中有一个用于滑块的 javascript 函数。当我们处于未调用滑块或没有触发元素的页面时,它会在控制台中显示错误“Uncaught TypeError:无法读取 null 的属性(读取‘querySelector’)”,滑块在页面中时不会显示此错误。

我想知道如何避免此错误,以及如何防止此函数在没有此滑块的页面中加载?

function slider(set) {
    const sliderContainer = document.querySelector(set.name),
        slider = sliderContainer.querySelector('.slider'),
        sliderItem = slider.querySelectorAll('.slider__item'),
    sliderArrows = sliderContainer.querySelectorAll('.arrows__item');
    
    let dotsCreate,
        dotsClass,
        dotsFunk,
        numberSlider,
        numberSliderWork,
        sliderExecutionLine,
    sliderExecutionLineWork;
    
    // calculate the maximum width of all slides
    function forSliderItem(t) {
        t = 0;
        for(let i = 0; i < sliderItem.length - 1; i++) {
            t += sliderItem[i].clientWidth;
        }
        return t;
  }
  
    let maxWidth = forSliderItem(sliderItem), // maximum width of all slides
        slidWidth = 0, // main variable for calculating the movement of the slider
    count = 0; // counter
    //===== flip left
    sliderArrows[0].addEventListener('click', function() {
        if(count !== 0) {
            count--;
            slidWidth -= sliderItem[count].clientWidth;
            slider.style.transform = `translateX(-${slidWidth}px)`;
        } else {
            count = sliderItem.length - 1;
            slidWidth = maxWidth;
            slider.style.transform = `translateX(-${slidWidth}px)`;
    }
        if(set.dots) {
            dotsFunk();
        }
        if(set.numberSlid) {
            numberSliderWork(count);
        }
        if(set.line) {
            sliderExecutionLineWork(count);
        }
  });
  
    //===== flip right  
    sliderArrows[1].addEventListener('click', function() {
        if(count < sliderItem.length - 1) {
            count++;
            slidWidth += sliderItem[count].clientWidth;
            slider.style.transform = `translateX(-${slidWidth}px)`;
        } else {
            count = 0;
            slidWidth = 0;
            slider.style.transform = `translateX(-${slidWidth}px)`;
    }
        if(set.dots) {
            dotsFunk();
        }
        if(set.numberSlid) {
            numberSliderWork(count);
        }
        if(set.line) {
            sliderExecutionLineWork(count);
        }
  });
  
    //===== dots
    if(set.dots) {
        dotsCreate = function() {
            const dotContainer = document.createElement('div'); // create dots container
            dotContainer.classList.add('dots');
            // create the required number of dots and insert a container into the dots
            sliderItem.forEach(() => {
                let dotsItem = document.createElement('span');
                dotContainer.append(dotsItem);
            });
            sliderContainer.append(dotContainer);
        };
    dotsCreate();
    
        // add the class to the desired dots, and remove from the rest
        dotsClass = function(remove, add) {
            remove.classList.remove('dots_active');
            add.classList.add('dots_active');
    };
    
        // move slides by clicking on the dot
        dotsFunk = function() {
            const dotsWork = sliderContainer.querySelectorAll('.dots span'); // we get dots
            dotsWork.forEach((item, i) => {
                dotsClass(dotsWork[i], dotsWork[count]);
                item.addEventListener('click', function() {
                    count = i;
                    // multiply the slide size by the number of the dots, and get the number by which you need to move the slider
                    slidWidth = sliderItem[0].clientWidth * i;
                    slider.style.transform = `translateX(-${slidWidth}px)`;
                    for(let j = 0; j < dotsWork.length; j++) {
                        dotsClass(dotsWork[j], dotsWork[count]);
                    }
                    if(set.dots && set.numberSlid) {
                        numberSliderWork(count);
                    }
                    if(set.line) {
                        sliderExecutionLineWork(count);
                    }
                }); 
            });
        };
        dotsFunk();
  }
  
    //=====  count slider
    if(set.numberSlid) {
        numberSlider = function(item) {
            const countContainer = document.createElement('div'),
                sliderNumber = document.createElement('span'),
                slash = document.createElement('span'),
                allSliderNumber = document.createElement('span');
        casClient = document.createElement('p');
            sliderNumber.innerHTML = item + 1;
      casClient.innerHTML = 'Cas client N°';
            slash.innerHTML = '/';
            allSliderNumber.innerHTML = sliderItem.length;
            countContainer.classList.add('count-slides');
            countContainer.append(casClient, sliderNumber, slash, allSliderNumber);
            sliderContainer.append(countContainer);
        };
    numberSlider(0);
    
        numberSliderWork = function(item) {
            const sliderNumberNow = sliderContainer.querySelector('.count-slides span');
            sliderNumberNow.innerHTML =  item + 1;
            if(set.line) {
                sliderExecutionLineWork(item);
            }
        };
  }
}
slider({
    name: ".video_users",
    numberSlid: true
});
<!DOCTYPE html>
<html lang="fr">

<head>
  <title>Example of a page without the slider</title>
</head>

<body class="error_404">
  <h1>Example of a page without the slider</h1>

  <script src="media/js/faveod.js" async></script>
</body>

</html>
2个回答

如果不希望显示错误,则只需在元素不存在时返回即可。

const sliderContainer = document.querySelector(set.name);
if (!sliderContainer) return;
const slider = sliderContainer.querySelector('.slider'),
      sliderItem = slider.querySelectorAll('.slider__item'),
      sliderArrows = sliderContainer.querySelectorAll('.arrows__item');

如果您希望它仅在某些页面上执行,则只需添加:

if (location.pathname !== '/the/page/with/slider') return;

到函数的开头

skara9
2021-12-01
/*
* SCROLLBAR 2 COLUMN / SOLUTIONS
*/
var ssb = {
  aConts  : [],
  mouseY : 0,
  N  : 0,
  asd : 0, /*active scrollbar element*/
  sc : 0,
  sp : 0,
  to : 0,
  
  // constructor
  scrollbar : function (cont_id) {
    var cont = document.getElementById(cont_id);
    
    // perform initialization
    if (! ssb.init()) return false;
    
    var cont_clone = cont.cloneNode(false);
    cont_clone.style.overflow = "hidden";
    cont.parentNode.appendChild(cont_clone);
    cont_clone.appendChild(cont);
    cont.style.position = 'absolute';
    cont.style.left = cont.style.top = '0px';
    cont.style.width = cont.style.height = '100%';
    
    // adding new container into array
    ssb.aConts[ssb.N++] = cont;
    
    cont.sg = false;
    
    //creating scrollbar child elements
    cont.st = this.create_div('ssb_st', cont, cont_clone);
    cont.sb = this.create_div('ssb_sb', cont, cont_clone);
    cont.su = this.create_div('ssb_up', cont, cont_clone);
    cont.sd = this.create_div('ssb_down', cont, cont_clone);
    
    // on mouse down processing
    cont.sb.onmousedown = function (e) {
      if (! this.cont.sg) {
        if (! e) e = window.event;
        
        ssb.asd = this.cont;
        this.cont.yZ = e.screenY;
        this.cont.sZ = cont.scrollTop;
        this.cont.sg = true;
        
        // new class name
        this.className = 'ssb_sb ssb_sb_down';
      }
      return false;
    }
    // on mouse down on free track area - move our scroll element too
    cont.st.onmousedown = function (e) {
      if (! e) e = window.event;
      ssb.asd = this.cont;
      
      ssb.mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
      for (var o = this.cont, y = 0; o != null; o = o.offsetParent) y += o.offsetTop;
      this.cont.scrollTop = (ssb.mouseY - y - (this.cont.ratio * this.cont.offsetHeight / 2) - this.cont.sw) / this.cont.ratio;
      this.cont.sb.onmousedown(e);
    }
    
    // onmousedown events
    cont.su.onmousedown = cont.su.ondblclick = function (e) { ssb.mousedown(this, -1); return false; }
    cont.sd.onmousedown = cont.sd.ondblclick = function (e) { ssb.mousedown(this,  1); return false; }
    
    //onmouseout events
    cont.su.onmouseout = cont.su.onmouseup = ssb.clear;
    cont.sd.onmouseout = cont.sd.onmouseup = ssb.clear;
    
    // on mouse over - apply custom class name: ssb_sb_over
    cont.sb.onmouseover = function (e) {
      if (! this.cont.sg) this.className = 'ssb_sb ssb_sb_over';
      return false;
    }
    
    // on mouse out - revert back our usual class name 'ssb_sb'
    cont.sb.onmouseout  = function (e) {
      if (! this.cont.sg) this.className = 'ssb_sb';
      return false;
    }
    
    // onscroll - change positions of scroll element
    cont.ssb_onscroll = function () {
      this.ratio = (this.offsetHeight - 2 * this.sw) / this.scrollHeight;
      this.sb.style.top = Math.floor(this.sw + this.scrollTop * this.ratio) + 'px';
    }
    
    // scrollbar width
    cont.sw = 16;
    
    // start scrolling
    cont.ssb_onscroll();
    ssb.refresh();
    
    // binding own onscroll event
    cont.onscroll = cont.ssb_onscroll;
    return cont;
  },
  
  // initialization
  init : function () {
    if (window.oper || (! window.addEventListener && ! window.attachEvent)) { return false; }
    
    // temp inner function for event registration
    function addEvent (o, e, f) {
      if (window.addEventListener) { o.addEventListener(e, f, false); ssb.w3c = true; return true; }
      if (window.attachEvent) return o.attachEvent('on' + e, f);
      return false;
    }
    
    // binding events
    addEvent(window.document, 'mousemove', ssb.onmousemove);
    addEvent(window.document, 'mouseup', ssb.onmouseup);
    addEvent(window, 'resize', ssb.refresh);
    return true;
  },
  
  // create and append div finc
  create_div : function(c, cont, cont_clone) {
    var o = document.createElement('div');
    o.cont = cont;
    o.className = c;
    cont_clone.appendChild(o);
    return o;
  },
  // do clear of controls
  clear : function () {
    clearTimeout(ssb.to);
    ssb.sc = 0;
    return false;
  },
  // refresh scrollbar
  refresh : function () {
    for (var i = 0, N = ssb.N; i < N; i++) {
      var o = ssb.aConts[i];
      o.ssb_onscroll();
      o.sb.style.width = o.st.style.width = o.su.style.width = o.su.style.height = o.sd.style.width = o.sd.style.height = o.sw + 'px';
      o.sb.style.height = Math.ceil(Math.max(o.sw * .5, o.ratio * o.offsetHeight) + 1) + 'px';
    }
  },
  // arrow scrolling
  arrow_scroll : function () {
    if (ssb.sc != 0) {
      ssb.asd.scrollTop += 6 * ssb.sc / ssb.asd.ratio;
      ssb.to = setTimeout(ssb.arrow_scroll, ssb.sp);
      ssb.sp = 32;
    }
  },
  
  /* event binded functions : */
  // scroll on mouse down
  mousedown : function (o, s) {
    if (ssb.sc == 0) {
      // new class name
      o.cont.sb.className = 'ssb_sb ssb_sb_down';
      ssb.asd = o.cont;
      ssb.sc = s;
      ssb.sp = 100;
      ssb.arrow_scroll();
    }
  },
  // on mouseMove binded event
  onmousemove : function(e) {
    if (! e) e = window.event;
    // get vertical mouse position
    ssb.mouseY = e.screenY;
    if (ssb.asd.sg) ssb.asd.scrollTop = ssb.asd.sZ + (ssb.mouseY - ssb.asd.yZ) / ssb.asd.ratio;
  },
  // on mouseUp binded event
  onmouseup : function (e) {
    if (! e) e = window.event;
    var tg = (e.target) ? e.target : e.srcElement;
    if (ssb.asd && document.releaseCapture) ssb.asd.releaseCapture();
    
    // new class name
    if (ssb.asd) ssb.asd.sb.className = (tg.className.indexOf('scrollbar') > 0) ? 'ssb_sb ssb_sb_over' : 'ssb_sb';
    document.onselectstart = '';
    ssb.clear();
    ssb.asd.sg = false;
  }
} 

window.onload = function() {
ssb.scrollbar('container'); // scrollbar initialization
}
Tony
2021-12-01