如何将元素id作为函数参数

时间:2018-01-29 07:19:58

标签: javascript

我正在学习前端开发人员。我是javascript的新手。当我从后端执行一个js传递一些元素id时,我遇到了这个问题。它显示一些错误无法读取属性' addEventListener'为null 。 我的js:

function disableOtherCheckBoxGrpScrolls(elementsContainerId) {
   console.error("Elements id from backend: " + elementsContainerId);
   var container = document.getElementById(elementsContainerId);
   // I am checking here length of elements
   console.error("Elements length : " + container.length);
   // It displays Elements length : undefined
     container.addEventListener('mousewheel', function(e){
      if (!$(this).hasScrollBar()) return;
     // If container div has a scrollbar it will do nothing

        var event = e.originalEvent,
        d = event.wheelDelta || -event.detail;

        this.scrollTop += (d < 0 ? 1 : -1) * 30;
        e.preventDefault();  
    }, {passive: false});
}

这有什么解决方案吗?

我的后端传递元素id

    if (!isMobile)
        JSUtil.execFn("disableOtherCheckBoxGrpScrolls", checkboxGrp.getElementsContainerId());

3 个答案:

答案 0 :(得分:1)

伙计们我解决了我的问题:)。但我不明白这是如何工作的。我的解决方案是:

function disableOtherCheckBoxGrpScrolls(elementsContainerId) {
  console.error('containerId: ' + elementsContainerId);
  // First is element undefined or Not rendered to DOM my opinion
  (function() {
    if (typeof elementsContainerId === "undefined") {
        throw new Error("elementsContainerId parameter is undefined");
    }
    var container = document.getElementById(elementsContainerId);
    console.error("Elements ID : " + container.length);
    container.addEventListener('mousewheel', function(e) {
        if (!$(this).hasScrollBar()) return;
        // logger.debug('has scroll');

        var event = e.originalEvent,
            d = event.wheelDelta || -event.detail;

        this.scrollTop += (d < 0 ? 1 : -1) * 30;
        e.preventDefault();
     }, { passive: false });

  })();

}

我认为也许js在html元素没有加载之前工作我发现null and undefined错误。顺便感谢所有评论和答案:)。

答案 1 :(得分:0)

确保在调用时传递函数参数。

disableOtherCheckBoxGrpScrolls(&#39; yourIDElement&#39);

答案 2 :(得分:0)

您应该检查您的elementsContainerId参数是不是undefined还是null。在某些地方,您在没有参数的情况下调用disableOtherCheckBoxGrpScrolls,使用未定义的变量,其变量的值为null

您可以在逻辑之前检查elementsContainerId不是undefinednull,如果条件为真,则会抛出错误。这样,您将立即注意到您是否向您的函数传递了错误的参数。

function disableOtherCheckBoxGrpScrolls(elementsContainerId) {
   if(typeof elementsContainerId === "undefined" || elementsContainerId === null) {
       throw new Error("elementsContainerId parameter is undefined or null");
   }
   // ...
}

此外,在第一次验证之后,您可以检查具有指定id的元素是否存在(只是为了保证绑定mousewheel事件)

相关问题