简体   繁体   English

Jquery/Javascript 无法设置包含页面 html 的属性 innerHTML

[英]Jquery/Javascript cannot set property innerHTML with include a page html

I include a page html in other page.我在其他页面中包含一个页面 html。 In the included page I have a element with an Id.在包含的页面中,我有一个带有 Id 的元素。 I try change the element from the other page but I have a error: Uncaught TypeError: Cannot set property 'innerHTML' of null我尝试从其他页面更改元素,但出现错误:Uncaught TypeError: Cannot set property 'innerHTML' of null

Part.html部分.html

<h1 id="Title">Hello</h1>

Index.html索引.html

<html>
<head>
    <title></title>
    <script src="jquery.min.js"></script>
</head>
<body>
    <div id="PartDiv"></div>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#PartDiv').load('/Part.html');
        });
    </script>

    <script type="text/javascript">
        function funct1() {
            document.getElementById("Title").innerHTML = "Bye";
        }
        funct1();
    </script>

</body>
</html>

A couple potential issues: first, your DOM element id is "title", not "Title".几个潜在问题:首先,您的 DOM 元素id是“标题”,而不是“标题”。 So your function should be:所以你的功能应该是:

function funct1() {
  document.getElementById("title").innerHTML = "Bye";
}

The next potential issue is that the jQuery load method is asynchronous, so you'll want to make sure you execute funct1 function in the load callback to make sure the DOM element has been loaded fist:下一个潜在问题是 jQuery load方法是异步的,因此您需要确保在load回调中执行funct1函数以确保 DOM 元素已被加载:

$('#PartDiv').load('/Part.html', funct1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM