代码之家  ›  专栏  ›  技术社区  ›  user8439189

无法读取未定义的属性“scrollHeight”-脚本中应修复的内容

  •  -5
  • user8439189  · 技术社区  · 8 年前

    我遇到了一个脚本问题,它会自动单击“跟随”按钮。

    以下是我的代码:

    var jq = document.createElement('script');
    jq.src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"; //Loads JavaScript
    document.getElementsByTagName('head')[0].appendChild(jq);
    jQuery.noConflict()

    window.setInterval(function(){
    var x = 0;
    $("button:contains('Follow')").each(
    function(){ if($(this).text()=="Follow"){
    if(x==2) return false; 
    $(this).trigger("click");
    $('._4gt3b').scrollTop($('._4gt3b')[0].scrollHeight);
    x++;}
    }
    )
    $('._4gt3b').scrollTop($('._4gt3b')[0].scrollHeight); console.log('loop');
    }, 70000); 

    VM160:7 Uncaught TypeError: Cannot read property 'scrollHeight' of undefined
        at HTMLButtonElement.<anonymous> (<anonymous>:7:39)
        at Function.each (jquery.min.js:2)
        at n.fn.init.each (jquery.min.js:2)
        at <anonymous>:3:32
    1 回复  |  直到 8 年前
        1
  •  0
  •   Muthu Kumaran    8 年前

    为避免错误,请检查元素是否存在。添加了一个条件以检查元素是否存在或未定义 if(typeof $('._4gt3b')[0] !== 'undefined')

    这是经过修改的脚本,缩进适当,

    window.setInterval(function(){
      var x = 0;
      $("button:contains('Follow')").each(function(){ 
        if($(this).text()=="Follow"){
          if(x==2) return false; 
          $(this).trigger("click");
          if(typeof $('._4gt3b')[0] !== 'undefined'){
            $('._4gt3b').scrollTop($('._4gt3b')[0].scrollHeight);
          }
          x++;
        }
      });
      if(typeof $('._4gt3b')[0] !== 'undefined'){
        $('._4gt3b').scrollTop($('._4gt3b')[0].scrollHeight);
      }
      console.log('loop');
    }, 70000);