【问题标题】:wrap everything between hr elements将所有内容包裹在 hr 元素之间
【发布时间】:2017-12-04 17:13:32
【问题描述】:

试图找到一种方法在代码中的 hr 标记之间包装所有内容,但到目前为止还没有。对代码有什么建议吗?

这是我现在正在做的事情(也作为fiddle):

$('hr').each(function() {
  $(this).next('hr').wrapAll('<div style="background-color:yellow"></div>');
});
Text
<hr>
Text1
Text2
<hr>
Text3
<hr>
Text4
Text5
<hr>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【问题讨论】:

  • “请看小提琴” 请使用堆栈片段([&lt;&gt;] 工具栏按钮;here's how to do one)。 (编辑:这次我已经为你做了。)
  • 谢谢TJ,现在我知道未来了
  • @T.J.Crowder 你忘记了 jQuery 脚本参考。
  • @MasterYoda:非常简短。 :-)
  • 以为我包含在 jsfiddle 中。但是你的修正仍然没有变成黄色。也许我错过了什么?

标签: jquery wrapall


【解决方案1】:

jQuery 对文本节点的帮助并不多(contents 除外)。这里最简单的可能就是使用 DOM 本身来查找以下兄弟节点(包括文本节点),然后将它们包装在 div; 中。见 cmets:

$('hr').each(function() {
  // Build an array of all nodes (including text nodes)
  // up to and not including the next HR if any
  var nodes = [];
  var n = this.nextSibling;
  while (n && n.nodeName != "HR") {
    nodes.push(n);
    n = n.nextSibling;
  }
  // Wrap them in a div
  $(nodes).wrapAll('<div style="background-color:yellow"></div>');
});
Text
<hr>
Text1
Text2
<hr>
Text3
<hr>
Text4
Text5
<hr>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • @t-j-crowder,只是快速跟进。在 html 文件中工作正常,但是当我更改为 xhtml 格式时,它的行为有点奇怪(所有结束的 div 都聚集在一起,而不是在每个小时之后结束)。 hr 标签是 xhtml 与
    兼容的,你知道代码中的什么可能导致 xhtml 出现这种情况吗?
  • @KevinLindmark:以上是在 DOM 级别工作的; DOM 是如何构建的(HTML、XHTML)并不重要,它应该仍然可以工作。并且似乎:jsbin.com/sojavuketo/1/edit?html,js,output
  • @t-j-crowder 是的,在我的生产代码中肯定是其他东西造成了我的问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多