简体   繁体   English

如何改变<p>标记文本,不删除下划线或斜体格式?

[英]How to change <p> tag text, without remove underline or italic format?

I have this situation我有这种情况

"<p><strong><em><u>Allow Ship Partial</u></em></strong></p>"

I want to change the <p> text but if use $('p').text('another text') it will be remove the text format.我想更改<p>文本,但如果使用$('p').text('another text')它将删除文本格式。

There is any way that I can do that without loose the format?有什么方法可以在不丢失格式的情况下做到这一点?

This happens because you're replacing the content of p with another text which happens to be发生这种情况是因为您正在用另一个文本替换 p 的内容,而该文本恰好是

<strong><em><u>Allow Ship Partial</u></em></strong></p>

So you're replacing even the format tags.所以你甚至要替换格式标签。 You should instead use你应该改用

$('p strong em u').text('another text')

or even better甚至更好

 $('p>strong>em>u').text('another text')

You could alternatively use CSS for the styling of the您也可以使用 CSS 来设置样式

tag标签

it would look something like this它看起来像这样

p {
    font-weight: bold;
    font-style: italic;
    text-decoration: underline;
}

Grab the parent of p using parentNode , iterate over the child nodes and append them to the parent , and then delete the original node.使用parentNode p的父节点,遍历子节点并将它们附加到parent ,然后删除原始节点。

    while(c.hasChildNodes()) p.appendChild(c.firstChild);
    p.removeChild(c);

 let c = document.querySelector("p"), p = c.parentNode; while(c.hasChildNodes()) p.appendChild(c.firstChild); p.removeChild(c);
 <p><strong><em>Hi</em></strong></p>

While the other answers may tackle your problem if your structure is always guaranteed (which I don't believe it is), then you can instead iterate recursively over child nodes until you find a text node.如果您的结构始终得到保证(我不相信),其他答案可能会解决您的问题,但您可以改为递归迭代子节点,直到找到文本节点。 Once you have that, replace the text inline.完成后,替换内联文本。

 function findTextElement(element) { for (let i = 0, n = element.childNodes.length; i < n; i++) { const child = element.childNodes[i]; if (child.nodeType !==3) { return findTextElement(child); } return child; } } const ps = document.querySelectorAll('p'); [].forEach.call(ps, (node, i) => { const textElement = findTextElement(node); textElement.parentNode.innerHTML = `New String ${i + 1} retains formatting`; });
 <p><strong><em><u>Allow Ship Partial 1</u></em></strong></p> <p><em><strong>Allow Ship Partial 2</strong></em></p> <p><u>Allow Ship Partial 3</u></p> <p>Allow Ship Partial 4</p>

Note this example is just a first pass;注意这个例子只是第一遍; there are most likely edge cases you will need to check against (like whether or not a text node is found, etc.).您最有可能需要检查边缘情况(例如是否找到文本节点等)。 I've also not used jQuery as most jQuery methods do not include text nodes.我也没有使用 jQuery,因为大多数 jQuery 方法不包含文本节点。 You may be able to refactor this using jQuery.contents() if you prefer that route, filtering out non-text nodes on each iteration.如果您更喜欢该路由,您可以使用jQuery.contents()对其进行重构,在每次迭代时过滤掉非文本节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM