且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery nextUntil包含文本节点

更新时间:2023-11-07 11:54:34

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

Only the jQuery .contents() method returns all nodes (including text nodes, normally ignored).

那么可能是这样的?:

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>');
    }
});

它只是迭代所有节点,并根据标志启动新集合,或包装找到的节点。

It just iterate all nodes and based on a flag starts a new collection, or wraps the nodes found.

最后的 if(open)允许内容中的未闭合的spolier块入级div。

The final if (open) allows for an unclosed spolier block within a content classed div.

注意:


  • $()是一个空的jQuery集合(就像一个空数组,但是对于jQuery对象)

  • 我建议你使用一个样式为你的剧透和使用一个类,例如 result.wrapAll('< div class =spoiler>< / div>');

  • $() is an empty jQuery collection (like an empty array but for jQuery objects)
  • I suggest you use a style for your spoilers and use a class e.g. result.wrapAll('<div class="spoiler"></div>');

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