javascript - 使用 javascript 加载元素然后应用它们 javascript

标签 javascript jquery html css

我正在尝试使用 jquery .load("file") 函数加载“header.html”,将 css 应用于加载的元素(有效),然后将 JS 应用于加载的元素,滚动上的 float 菜单等功能,但是它不起作用。这是我在头部导入文件的顺序:

<!-- Elements going to be loaded are using this font-awesome css
so they must be loaded before anything -->
<link rel="stylesheet" href="awesome/css/font-awesome.min.css" />

<!-- Then importing the jquery -->
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<!-- This is the point where i load the header.html -->
<script src="js/indexLoad.js"></script>

<!-- Then apply css to the loaded elements (works) -->
<link rel="stylesheet" href="css/index.css" />

<!-- Then apply JS to the loaded elements (doesnt work) -->
<script src="js/index.js"></script>

在 header.html 中,我导入了一些元素,例如 nav
然后将样式更改为 nav 以将其显示为红色。
当我在 index.js 中使用 var newHeight = $("nav").position().top 我只是得到 cannot read property value of null... 为什么 css 将样式应用于加载的元素,而 JS 却无法获取它们?

我在两个 .js 文件中正确使用了 $(document).ready( function(){}:

indexLoad.js

$(document).ready( function(){
    $("header").load("http://localhost/js/header.html");
});

索引.js

$(document).ready( function(){
var newHeight = $("nav").position().top;
});

最佳答案

总是 首先加载所有的 CSS 文件,然后是 JS 脚本。总是。

并且所有访问DOM元素的JS都需要在DOM就绪后加载。通过使用其中一个处理程序(如 $(document).ready)或简单地将脚本放在 HTML 主体的末尾。 (不确定您是否对所有脚本都这样做,您可能是)

由于您正在使用 AJAX 调用来加载 header ,因此您需要等待它加载以便 JS 可以使用 nav 元素。因此,使用 load() 回调函数来执行所有操作 header 标记的操作。


关键内容:由于您要分别加载 index.js 和 indexLoad.js,因此您实际上需要在它们之间进行某种协调。我建议在 index.js 文件中设置一个事件监听器,并在 header 准备好后在 indexLoad.js 中触发该事件(在 load() 回调中)。像这样:

indexLoad.js

$(document).ready( function(){
    $("header").load("http://localhost/js/header.html", function() {
        $('body').trigger('headerReady');
    });
});

索引.js

$('body').on('headerReady', function(){
    var newHeight = $("nav").position().top;
    // everything else that requires header elements goes here
    // or under a similar listener
});

这是一个简单的 snipper,它使用超时来模拟异步调用延迟:

setTimeout(function(){
  $('body').append('<nav>Nav here</nav>');
  $('body').trigger('headerReady'); // simulating a 3s delay
  }, 3000);

$('body').on('headerReady', function() {
  alert('header is ready');
  $('nav').css('color', 'green');
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

关于javascript - 使用 javascript 加载元素然后应用它们 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27468888/

相关文章:

javascript - 从 JavaScript 调用 Objective C 方法的最简单方法(无需插件)?

javascript - jQuery on() 与其前身的性能对比 [live()、bind()、delegate()]

javascript - 为什么键盘(onKeyDown)事件冒泡在组件上无法访问,但在父级上?

javascript - 你如何引用 Array.prototype.slice.call()?

jquery - 查找 div 元素并使用 jquery 替换 value-innerhtml

javascript - 隐藏/显示 HTML 表格

php/css/html 语言按钮当前语言

Python Django 搜索中的多个属性

javascript - sleep() 的 JavaScript 版本是什么?

jQuery 多复选框过滤器组