jQuery在ngView加载的元素[AngularJS]上找不到元素

jQuery cant find element on ngView loaded elements [AngularJS]

本文关键字:元素 AngularJS 找不到 jQuery ngView 加载      更新时间:2023-09-26

我正试图获取app.js控制的ngView中存在的元素<div class='profile'></div>offset().top,但控制台显示错误:

未捕获的类型错误:无法读取未定义的属性"top"

jQuery代码:

var topOfOthDiv = $('.profile').offset().top;

索引.ejs

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="main/js/main.js"></script>
    ...
</head>
    <body>
       <div class="ui inverted top fixed nbar hidden menu">...</div>
       <div class="ui main container " ng-view>
       </div>
    </body>

main.js

$(document)
    .ready(function() {
        var topOfOthDiv = $('.profile').offset().top;
        $(window).scroll(function() {
                if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div?
                    $('.fixed.menu').transition('fade in'); //reached the desired point -- show div
                }
                if($(window).scrollTop() < topOfOthDiv) { //scrolled past the other div?
                    $('.fixed.menu').transition('fade out'); //reached the desired point -- show div
                }
            });
    })
  ;

ng-view中,我加载了具有.profile clssdiv的不同视图如果.profile类位于index.ejs

中,则代码运行良好

如果不查看整个代码,我们就无法真正说出原因,因为这可能有很多原因,但最可能的原因是:

  1. 在声明HTML之后加载Javascript文件。这意味着脚本正在寻找在执行后写入浏览器的内容
  2. 您没有正确加载jQuery