这是关于 HTML <object>
元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>parent</title>
<style>
#square { width:20px; height:20px; background-color: aqua;}
</style>
</head>
<body>
<div id="square"></div>
<object data="child.html" type="text/html" ></object>
</body>
</html>
和child.html是:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<button>red</button>
<button>blue</button>
<script>
document.querySelectorAll('button').forEach(bt=>{
bt.onclick=e=>{
console.log(e.target.textContent)
document.parentNode.getElementById('square').style.background = e.target.textContent
}
})
</script>
</body>
</html>
但是我得到了这个错误:
TypeError: document.parentNode is null
那么如何在 JS 中访问 child.html 中的#square 元素?
最佳答案
试试这个 -
parent.document.getElementById('square').style.background = e.target.textContent
关于javascript - 如何从javascript中的html对象访问父文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497995/