jquery 插入html
使用 jQuery 插入 HTML 的方法
使用 append() 方法
append() 方法将内容插入到选定元素的内部末尾。
示例代码:
$("#targetElement").append("<p>This is appended content.</p>");
使用 prepend() 方法
prepend() 方法将内容插入到选定元素的内部开头。
示例代码:
$("#targetElement").prepend("<p>This is prepended content.</p>");
使用 after() 方法
after() 方法将内容插入到选定元素的外部之后(同级)。
示例代码:

$("#targetElement").after("<p>This is inserted after.</p>");
使用 before() 方法
before() 方法将内容插入到选定元素的外部之前(同级)。
示例代码:
$("#targetElement").before("<p>This is inserted before.</p>");
使用 html() 方法
html() 方法直接替换选定元素的全部内部 HTML。
示例代码:

$("#targetElement").html("<p>This replaces all content.</p>");
使用 text() 方法
text() 方法插入纯文本内容(不解析 HTML 标签)。
示例代码:
$("#targetElement").text("This is plain text.");
动态插入 HTML 的注意事项
- 安全性:避免直接插入未转义的用户输入,防止 XSS 攻击。
- 性能:频繁操作 DOM 可能影响性能,建议批量插入内容。
- 链式调用:jQuery 方法支持链式调用,可组合使用。
示例:$("#targetElement") .append("<div>First</div>") .prepend("<div>Second</div>");
结合动态数据插入
可通过变量或函数动态生成 HTML 内容。
示例:
const dynamicContent = "<span>Dynamic: " + new Date() + "</span>";
$("#targetElement").append(dynamicContent);






