要 hook appendChild
方法并打印所添加节点的 HTML 内容,你可以重写原始的 appendChild
方法,并在其中获取新添加节点的 HTML。以下是一个示例代码,展示如何实现这个功能:
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hook appendChild</title>
</head>
<body>
<div id="parent"></div>
<script>
// 保存原始的 appendChild 方法
const originalAppendChild = Node.prototype.appendChild;
// 重写 appendChild 方法
Node.prototype.appendChild = function(child) {
// 在调用原始方法之前进行处理
if (child instanceof HTMLElement) {
console.log("Appending element with innerHTML:", child.innerHTML);
}
// 调用原始的 appendChild 方法
return originalAppendChild.call(this, child);
};
// 创建并添加一个新的元素节点
const newElement = document.createElement("div");
newElement.innerHTML = "<strong>Hello, I'm a new node!</strong>";
const parentNode = document.getElementById('parent');
parentNode.appendChild(newElement); // 此时会触发 hook
</script>
</body>
</html>
解释
保存原始方法:
const originalAppendChild = Node.prototype.appendChild;
我们首先保存原来的
appendChild
方法,以便后续调用。重写
appendChild
:Node.prototype.appendChild = function(child) {
if (child instanceof HTMLElement) {
console.log("Appending element with innerHTML:", child.innerHTML);
}
return originalAppendChild.call(this, child);
};
- 在这里,我们定义了新的
appendChild
函数。当任何节点调用此方法时,它将被执行。 - 我们使用
instanceof HTMLElement
检查传入的参数是否为一个元素节点(而非文本节点等其他类型)。 - 如果是,则打印该元素的
innerHTML
。
创建并添加新元素节点: “`javascript const newElement = document.createElement(“div”); newElement.innerHTML = “Hello, I’m a new node!”;
const parentNode = document.getElementById(‘parent’);
parentNode.appendChild(newElement); // 此时会触发 hook “`
当你运行这个示例时,控制台将打印出 “Appending element with innerHTML: Hello, I’m a new node!“,这表明我们成功地 hook 了 appendChild
并能够打印新添加节点的 HTML 内容。
内容由零声教学AI助手提供,问题来源于学员提问