JavaScript包装解开的纯文本 [英] JavaScript wrapping unwrapped plain text

查看:98
本文介绍了JavaScript包装解开的纯文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一些非静态内容,我需要将所有未打开的纯文本包含在一个带有类的锚点元素中,但是我需要保留该文本的位置。

I have some non-static content on my webpage and I need all unwrapped plain text to be wrapped inside an anchor element with a class, however, I need to maintain the placement of that text.

我在本网站上搜索,并发现了一些问题,如这些,它们提出相同的问题,除了文本始终处于开头或结尾,答案总是将内容添加/追加到< div>

I've search around on this site and found questions like these which are asking the same question except the text is always in the beginning or the end and the answers always prepend/append the content back into the <div>.

为了使问题更加复杂,有些情况下,内容只会打开纯文本,我需要将其作为

To make the question even more complicated, there are scenarios where the content will be only unwrapped plain text and I'll need to wrap that as well.

我的HTML:

<div>
  <a>1</a>
  <a>2</a>
  3
  <a>4</a>
</div>

有时:

<div>
  1
</div>

我已尝试过这个页面,但都是重新排列文本。

I've tried all the answers on this page but they all reorder the text.

任何想法?

推荐答案

迭代元素的所有文本节点:

Iterate over all text nodes of the element:

$('div').contents().filter(function() {
    return this.nodeType === 3;
}).wrap('<a class="awesomeClass"></a>');

演示

.contents()检索元素的所有子节点,不仅元素节点。

.contents() retrieves all child nodes of the element, not only element nodes.

.filter 回调将丢弃不是文本节点的所有节点。它的工作原理如下:

每个DOM节点都有属性 nodeType 指定其类型(有什么惊喜)。该值是常数。元素节点的值为 1 ,文本节点的值为 3 .filter 将从回调返回的集合中删除所有元素 false

The .filter callback discards all nodes that are not text nodes. It works as follows:
Each DOM node has the property nodeType which specifies its type (what surprise). This value is a constant. Element nodes have the value 1 and text nodes have the value 3. .filter will remove all elements from the set for which the callback returns false.

然后每个文本节点都被包装在一个新元素中。

Then each of the text nodes is wrapped in a new element.


我有空白的问题。

I'm having a whitespace problem.

如果您的HTML看起来像

If your HTML looks like

<div>
  1
</div>

然后元素有一个子节点,一个文本节点。文本节点的值不仅包括可见字符,还包括所有空白字符,例如,开始标记后的换行符。在这里,它们是可见的(是一个空格,¬是换行符):

then the element has one child node, a text node. The value of the text node does not only consist of the visible character(s), but also of all the whitespace characters, e.g. the line break following the opening tag. Here they are made visible ( is a space, ¬ is a line break):

<div>¬
⋅⋅1¬
</div>

因此,文本节点的值为¬⋅⋅1¬

The value of the text node is therefore ¬⋅⋅1¬.

解决这个问题的方法是修剪节点值,删除尾随和前面的空格字符:

A way to solve this would be to trim the node values, removing trailing and preceding whitespace character:

$('div').contents().filter(function() {
    return this.nodeType === 3;
}).each(function() {
    this.nodeValue = $.trim(this.nodeValue);
}).wrap('<a class="awesomeClass"></a>');

DEMO

这篇关于JavaScript包装解开的纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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