我在 javascript 中的图像上有一个“单击”事件,我想用它来在单击时更改父元素的文本内容。但是,当我单击它时,父级的文本会发生变化,但图像会自行删除。我假设我可以在之后创建并附加一个新的子元素,但这似乎不是最有效的,而且我还想了解为什么子元素被删除。我的代码如下所示:
<body>
<ul>
<li> Hello <img src="img/hello.png"></li>
<ul>
<body>
<script>
const helloImage = document.querySelector('img')
helloImage.addEventListener('click', (e) => {
let parentEle = e.target.parentElement
parentEle.textContent = 'bye'
})
<script>
我已经寻找了一段时间的答案,但似乎找不到有关现代 JavaScript 的任何内容。我用 jQuery 找到了类似问题的答案,但在应用解决方案的逻辑时得到了相同的结果。任何帮助,或者如果您能给我指出正确的方向,我将非常感激。谢谢!
当您设置
textContent
时,您将覆盖所有其他子节点。
警告:在节点上设置 textContent 会删除该节点的所有子节点,并将它们替换为具有给定字符串值的单个文本节点。
textContent
设置者的
相应规格说
字符串将所有内容替换为其中给定的值。
如果您只想更改文本,请更改 HTML 并将要更改的文本包装在不同的元素中。然后在点击处理程序中引用该元素的
textContent
。
如果无法修改HTML-Structure,为了直接选择textContent,一种做法是复制该标签除textContent之外的所有子节点,等内容改变后再复制回来。
// Get the label you want to change
let label = document.getElementById("myLabelToChange");
// Copy the children to another array which is not updated by the node itself
let childrenStatic = [];
for (let i = 0; i < label.childNodes.length; i++){
// Skip the text node itself
if (label.childNodes[i].nodeType == Node.TEXT_NODE)
continue;
childrenStatic.push(label.childNodes[i]); // Take all other nodes
}
label.textContent = "new text of label"; // Change the text
// re-append all other nodes that
for (let i = 0; i < childrenStatic.length; i++){
label.appendChild(childrenStatic[i]);
}
这在我的用例中非常有效,其中 textContent 是第一个子项。在其他情况下,它可能会扰乱结构,必须采取进一步的措施。
这对我有用:
const helloImage = document.querySelector('img');
helloImage.addEventListener('click', (e) => {
helloImage.previousSibling.replaceData(0, 7, 'bye')
})
迟到总比不到好:)