使用 jQuery 更新 innerHTML
在今天的文章中,我们将学习如何在 jQuery 中更新或替换元素的内部 HTML。
使用 jQuery 更新 innerHTML
jQuery 提供了 .html()
方法来设置匹配元素集中每个元素的 HTML 内容。
语法:
.html(htmlString).html(function)
在调用函数之前,jQuery 会清空元素。然后它使用旧的 HTML 参数来查询旧的内容。this
可以引用函数内部集合中的当前元素。
当 .html()
用于设置元素的内容时,该元素中的任何内容都将完全替换为新内容。此外,在用全新的内容替换这些元素之前,jQuery 从子元素中去除了其他结构,如信息和事件处理程序。
此方法使用浏览器的 innerHTML
属性。
某些浏览器可能无法生成完全复制提供的 HTML 源的 DOM。使用 .text()
方法设置不包含 HTML 的 script
元素的内容,而不是使用 .html()
方法。
让我们通过以下示例来理解它。
HTML 代码:
<div class="txt-container">Hello World! Welcome to the DelftStack.</div>
<button type="button">Change the text</button>
JavaScript 代码:
$('button').click(() => {
$('div.txt-container')
.html('<p>Thank you for visiting <em>DelftStack!</em></p>');
})
在上面的例子中,我们定义了 div
元素,它打印 Hello World! Welcome to the DelftStack.
信息。当你单击 Change the text
按钮时,它将使用新的段落标签更新 DOM。
尝试在任何支持 jQuery 的浏览器中运行上面的代码片段。它将显示以下结果。
更改文本前的输出:
更改文本后的输出:
运行演示
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。