[英]Why doesn't my external javascript file work when I load my html page?
[英]When using .load() to insert an html file, javascript doesn't recognize elements and returns null
我正在使用 .load() 方法將 HTML 文件插入到我的頁面中,其中包含 SVG 信息。 但是,當我嘗試訪問導入的 SVG 文件中的元素時,我得到"Uncaught TypeError: Cannot read property 'addEventListener' of null"
這是 index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Party Packs</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="https://kit.fontawesome.com/c761a1adc3.js" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
</head>
<body>
<div id="insert-here"></div>
<script src="js/anime.min.js" charset="utf-8"></script>
<script src="js/index.js" charset="utf-8"></script>
</body>
</html>
然后這是我嘗試導入的 SVG 文件
<svg id="transmorph" width="100%" height="100%" viewBox="0 0 1920 1080" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
<path class="transmorph" d="M1920 0V1C1547.5 -118 1557 5 1450.5 1C1344 -3 1307 1 1224.5 1C1142 1 1105 1 899.5 1C693.414 1 698.5 1 567 1C421.424 1 345 -11.5 222 1C123.6 11 162 -12 0 1V0H1920Z" fill="#1a1a1a" />
</svg>
index.js 包含:
$(function() {
$('#transition-main-div').load('morph.html');
console.log(document.querySelector('#insert-here'));
});
如果我嘗試console.log('#insert-here');
在 index.js 文件中,它只返回 null。 我在互聯網上進行了搜索,我能找到的只是人們在 html 內容加載之前放置腳本的實例,但除非我遺漏了某些東西,否則情況並非如此。 謝謝。
load
是異步的。 在收到響應並將其添加到 DOM 之前,您已經在 DOM 中搜索其結果。 您需要根據文檔傳遞回調:
$('#transition-main-div').load('morph.html', function () {
console.log(document.querySelector('#insert-here'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.