jQuery next直到包含文本节点

jQuery nextUntil include text nodes

本文关键字:文本 节点 包含 next jQuery      更新时间:2023-09-26

我使用nextUntil方法来获取两个元素之间的所有内容。但是该方法不包括要输出的CCD_ 2。它给出了一个类似[<br>, <br>, <br>]的数组。如何获取包括文本节点在内的所有内容?

这是HTML代码:

$('.content a:contains("spoiler").b:even').each(function() {
  $(this).nextUntil('.content a:contains("spoiler").b')
    .wrapAll('<div style="border:solid 1px black;"></div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  --- <a class="b" href="/?q=spoiler">spoiler</a> ---
  <br>
  <br> dangerous text here
  <br> --- <a class="b" href="/?q=spoiler">spoiler</a> ---
  <br> safe text here
  <br> --- <a class="b" href="/?q=spoiler">spoiler</a> ---
  <br>
  <br> dangerous text here
  <br> --- <a class="b" href="/?q=spoiler">spoiler</a> ---
</div>

JSFiddle:http://jsfiddle.net/Lwk97rvq/1/

您可以创建自己的jquery插件,该插件与nextUntil相同,但包含文本节点:

$.fn.nextUntilWithTextNodes = function (until) {
    var matched = $.map(this, function (elem, i, until) {
        var matched = [];
        while ((elem = elem.nextSibling) && elem.nodeType !== 9) {
            if (elem.nodeType === 1 || elem.nodeType === 3) {
                if (until && jQuery(elem).is(until)) {
                    break;
                }
                matched.push(elem);
            }
        }
        return matched;
    }, until);
    return this.pushStack(matched);
};

所以你可以把这个叫nextUntilWithTextNodes而不是nextUntil,你就可以走了。

只有jQuery .contents()方法返回所有节点(包括文本节点,通常被忽略)。

也许是这样的?:

http://jsfiddle.net/ykv3gf5L/2/

$('.content').each(function () {
    var open = false;
    var result = $();
    $(this).contents().each(function () {
        var $this = $(this);
        if ($this.text() == "spoiler") {
            if (open) {
                result.wrapAll('<div style="border:solid 1px black;"></div>');
                open = false;
            } else {
                result = $();
                open = true;
            }
        } else {
            result = result.add($this)
        }
    });
    if (open) {
        result.wrapAll('<div style="border:solid 1px black;"></div>');
    }
});

它只是迭代所有节点,并基于一个标志启动一个新的集合,或者包装找到的节点。

最终的if (open)允许在content分类的分区中有一个未闭合的spolier块

注:

  • $()是一个空的jQuery集合(类似于空数组,但用于jQuery对象)
  • 我建议你对剧透使用一种风格,并使用一个类,例如result.wrapAll('<div class="spoiler"></div>');

例如。http://jsfiddle.net/ykv3gf5L/3/