jQuery - 将所有未包装的文本包装在p标签中 [英] jQuery - wrap all unwrapped text in p tags

查看:103
本文介绍了jQuery - 将所有未包装的文本包装在p标签中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下代码被写入我的页面的情况。

I have a situation where the following code is getting written to my page.

<div>
    Some text here which is not wrapped in tags
    <p>Some more text which is fine</p>
    <p>Blah blah another good line</p>
</div>

在这种情况下,它似乎总是第一行没有包装在p标签中尽管不是每次都能解决这个问题。有时很好。

In this case it always seems to be the first line which is not being wrapped in p tags which might make the solution to this easier, although it's not every time. Some times it is fine.

我需要做的是确定第一行是否被包装,如果没有,则包装它。

What I need to do is identify whether the first line is wrapped or not and if not then wrap it.

不幸的是我不知道从哪里开始这个问题所以任何帮助都会受到赞赏。

Unfortunately I'm not sure where to start with this problem so any help would be appreciated.

推荐答案

尝试使用此代码来包装任何未包含< p> 标记的TextNode。

Try using this code to wrap any TextNodes that are not wrapped with <p> tag.

function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], whitespace = /^\s*$/;

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || !whitespace.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
    }

    var textnodes = getTextNodesIn($("#demo")[0])​​​​;
    for(var i=0; i < textnodes.length; i++){
        if($(textnodes[i]).parent().is("#demo")){
            $(textnodes[i]).wrap("<p>");
        }
    }​

这里是 jsfiddle 显示了这一点。

PS:TextNode检测部分有借鉴了此答案

PS: TextNode detection part has been borrowed from this answer

这篇关于jQuery - 将所有未包装的文本包装在p标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆