jQuery .insertBefore():在目标前面插入兄弟元素

jQuery 的 .insertBefore() 将选中的内容紧接着插到每个目标前面。目标和插入的元素共享父元素。它可以将公告移到日程标题之前,也可以在指定项目之前添加内容。

在目标前面紧接着插入兄弟元素

$(content).insertBefore(target);

先选择要插入的元素。target 可以是选择器、DOM 元素或 jQuery 对象。文档对象模型(DOM)将文档表示为节点树。返回集合包含插入的元素,因此接着调用 .addClass() 会作用于这些元素。

jQuery 官方 .insertBefore() 文档

移动公告并测试按钮

将代码以 UTF-8 保存为 insert-before-example.html,然后用浏览器打开。示例从 CDN 加载 jQuery 4.0.0,需要联网。移动公告前后都试试公告内的按钮。

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>将公告移到日程标题之前</title>
  <style>
    body { margin: 1rem; font: 1rem/1.5 system-ui, sans-serif; overflow-wrap: anywhere; }
    main { max-width: 42rem; margin-inline: auto; }
    section { margin-block: .75rem; border: 1px solid #9eb1bf; border-radius: .4rem; padding: .75rem 1rem; }
    section h2 { font-size: 1.1rem; margin-top: 0; }
    button { font: inherit; margin: .15rem; padding: .35rem .55rem; }
    #notice { border: 1px solid #847045; padding: .45rem; }
    .highlight { background: #fff0ba; color: #3c2a06; }
  </style>
  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
  <main>
    <h1>将公告移到日程标题之前</h1>
    <button id="move" type="button">移到日程上方</button>
    <button id="restore" type="button">移回草稿区</button>
    <section id="draft" aria-labelledby="draft-title">
      <h2 id="draft-title">草稿区</h2>
      <div id="notice">
        <p>本周开放时间有变动。</p>
        <button id="confirm" type="button">确认公告</button>
        <p id="count" role="status">确认次数:0</p>
      </div>
    </section>
    <section id="schedule" aria-labelledby="schedule-title">
      <h2 id="schedule-title">日程</h2>
      <p>上午 9 点开始登记。</p>
    </section>
  </main>
  <script>
    $(function () {
      const $notice = $("#notice");
      let count = 0;
      $("#confirm").on("click", function () {
        count += 1;
        $("#count").text("确认次数:" + count);
      });
      $("#move").on("click", function () {
        $notice.insertBefore("#schedule-title").addClass("highlight");
      });
      $("#restore").on("click", function () {
        $notice.appendTo("#draft").removeClass("highlight");
      });
    });
  </script>
</body>
</html>
  1. 点击草稿区公告内的确认按钮。计数从 0 变成 1。
  2. 点击移到日程上方。公告移进日程区域,紧挨着标题之前。再次点击公告的确认按钮,计数变成 2。
  3. 点击移回草稿区,恢复原位置。刷新页面会同时重置位置和计数。

这个示例只有一个目标,原来的 #notice 和其中的按钮一起移动。点击处理函数仍然绑定在同一个按钮节点上,无需重新注册。

区分前一个兄弟元素和第一个子元素

方法 插入位置 返回的元素
.insertBefore() 紧挨目标之前,与目标共享父元素 插入的元素
.before() 紧挨目标之前,与目标共享父元素 目标元素
.insertAfter() 紧挨目标之后,与目标共享父元素 插入的元素
.prependTo() 目标内部的开头 插入的元素

$(target).before(content) 从目标开始,$(content).insertBefore(target) 从内容开始。两种写法的插入位置相同,可以根据下一步要操作哪些元素来选择。

jQuery 官方 .before() 文档

在示例页面的控制台运行此代码。它创建临时父元素,检查标题前的兄弟元素和父元素里的第一个子元素。

const $group = $("<div>");
const $target = $("<h2>").appendTo($group);
const $sibling = $("<p>").text("标题的前一个兄弟元素").insertBefore($target);
const $child = $("<p>").text("父元素的第一个子元素").prependTo($group);
console.log($target[0].previousElementSibling === $sibling[0]);
console.log($group[0].firstElementChild === $child[0]);

两行都输出 true。$sibling 紧挨在标题之前,$child 是父元素内部的第一个子元素。

在多处插入或添加新文本

有多个目标时,原节点放到最后一个目标之前,其他目标得到副本。如果要保留原位置,请插入用 .clone() 得到的副本。元素和后代复制来的 ID 应删除或改成唯一值。

要显示表单或 API 提供的字符串,可新建空元素并用 .text() 填入内容。在示例控制台运行代码,标题前会显示 <额外公告>,尖括号也会保留。刷新页面可清除该段落。

const message = "<额外公告>";
$("<p>").text(message).insertBefore("#schedule-title");

jQuery .text() 如何处理字符串

检查插入结果

  • 检查选择结果的 .length,并确认目标有父元素。插入兄弟元素需要共同的父元素。
  • 在开发者工具的元素面板确认目标和新元素共享父元素,而且新元素紧挨在目标前面。
  • 若选择器匹配多个标题,每个标题前面都会插入内容。只需改一处时,请缩小选择范围。

用 .insertAfter() 插入到目标之后 · 用 .prependTo() 插入到目标内部开头