首页 > 解决方案 > 在 jquery 中选择另一个文件中的元素

问题描述

如果打扰到您,开发人员很抱歉。所以让我们进入这个问题。伙计们也请考虑我正在使用nodejs和electronjs。关于目录的简单表示

main-doc
  |---src
       |---Html
       |     |---index.html
       |     |---navbar.html
       |
       |---svg
       |    |---home.svg   
       |
       |---js
            |---jquery-file.js

jquery 文件被导入到 index.html 以重用导航栏。所以我的jQuery代码,

$(".navbar-container").load("navbar.html")
console.log($(".icon-container")) // shows no element in console
$(".icon-container").load("../svg/home.svg") // icon-container is in navbar.html

所以我认为由于图标容器位于 navbar.html 中,因此在执行第二行时未正确加载。在这种情况下,如何使用 jquery 将此 svg 加载到我的代码中?

标签: javascriptjqueryhtmlnode.js

解决方案


.loadasync自然的。你可以观看on complete function。并在那里加载/工作。

样本:

$( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

你的情况:

$(".navbar-container").load("navbar.html", () => {
 console.log($(".icon-container")) // shows no element in console
 $(".icon-container").load("../svg/home.svg") // icon-container is in 
 navbar.html
})

阅读文档:https ://api.jquery.com/load/#load-url-data-complete


推荐阅读