jQuery 添加元素
jQuery:添加元素和内容
Section titled “jQuery:添加元素和内容”jQuery 使向 DOM 动态添加新的 HTML 元素或内容变得非常简单。
添加内容的方法
Section titled “添加内容的方法”有四种主要方法允许你将内容插入到所选元素相对位置:
append(): 将内容插入到每个所选元素的末尾(作为最后一个子元素)。prepend(): 将内容插入到每个所选元素的开头(作为第一个子元素)。after(): 将内容插入到每个所选元素的后面(作为下一个兄弟元素)。before(): 将内容插入到每个所选元素的前面(作为上一个兄弟元素)。
jQuery append() 方法
Section titled “jQuery append() 方法”在所选元素(们)内部,将其内容添加到末尾。
// 将文本添加到所有段落的末尾$("p").append("** -- Appended Text**");
// 将新的列表项添加到指定的列表中$("ul#my-list").append("<li>New Item</li>");jQuery prepend() 方法
Section titled “jQuery prepend() 方法”在所选元素(们)内部,将其内容添加到开头。
// 将文本添加到所有段落的开头$("p").prepend("**Prepended Text -- **");
// 将新的列表项添加到指定的列表中$("ul#my-list").prepend("<li>First Item</li>");使用 append() 和 prepend() 添加多个新元素
Section titled “使用 append() 和 prepend() 添加多个新元素”append() 和 prepend() 都可以接受多个参数,允许你一次添加多个新元素。这些元素可以创建为 HTML 字符串、jQuery 对象或原生 DOM 元素。
创建并 append/prepend 各种元素的示例:
$(function() { function addItems() { // 1. 使用 HTML 字符串创建元素 const item1 = "<li>Item from HTML string</li>";
// 2. 使用 jQuery 创建元素 const item2 = $("<li></li>").text("Item from jQuery object");
// 3. 使用原生 JavaScript DOM 方法创建元素 const item3 = document.createElement("li"); item3.textContent = "Item from DOM element";
// 将所有新项目添加到列表中 // 注意:使用 prepend(item1, item2, item3) 也可以 $("ul#my-list").append(item1, item2, item3); }
// 示例用法:点击按钮时添加项目 $("#add-button").on('click', addItems);});现代实践:JavaScript 模板字面量(反引号 `)通常方便用于创建多行或复杂的 HTML 字符串:const item =
;
jQuery after() 和 before() 方法
Section titled “jQuery after() 和 before() 方法”这些方法将内容插入到所选元素(们)的外部,作为兄弟元素。
after() 将内容插入到所选元素(们)紧随其后。
before() 将内容插入到所选元素(们)紧靠其前。
// 在图片后面插入文本$("img#logo").after("<p>Image caption</p>");
// 在图片前面插入文本$("img#logo").before("<h2>Logo Image:</h2>");使用 after() 和 before() 添加多个新元素
Section titled “使用 after() 和 before() 添加多个新元素”与 append() 和 prepend() 类似,after() 和 before() 也可以接受多个参数(HTML 字符串、jQuery 对象、DOM 元素),以便插入多个新元素作为兄弟元素。
创建并在图片后面插入各种元素的示例:
$(function() { function addContentAfterImage() { // 1. 使用 HTML 字符串创建元素 const text1 = "**Important: **";
// 2. 使用 jQuery 创建元素 const text2 = $("<i></i>").text("Review the image details. ");
// 3. 使用原生 JavaScript DOM 方法创建元素 const text3 = document.createElement("span"); text3.textContent = "(Last updated today)"; text3.style.fontSize = 'small'; // 样式化 DOM 元素的示例
// 在 id="product-image" 的图片后面插入新元素 // 注意:before(text1, text2, text3) 会将它们插入到图片前面 $("img#product-image").after(text1, text2, text3); }
// 示例用法 $("#add-details-button").on('click', addContentAfterImage);});jQuery HTML 操作参考
Section titled “jQuery HTML 操作参考”要全面了解所有用于操作 HTML 和 CSS 的 jQuery 方法,请查阅官方 jQuery 文档。