微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 从JQuery中的字符串中删除动态字符串

我有一个html字符串,其中包含一个标记.表标签中可能有各种标签(tr / td等).

如何保留我的字符串中的标记,同时保留其余的html?

即:

如果我的字符串是

"<p>testing<table><tr><td>cell 1</td></tr></table> a table</p>" 

然后我想要结果

"<p>testing a table</p>" 

编辑:

提供更多细节:我无法控制html,而p只是一个例子,它可以是标签之外的任何组合或纯文本(尽管只有1个表)

编辑2:

请参阅上文’如何从字符串中删除标记,同时保留其余的html?’这意味着如果(在表外)有一个粗体或强调的元素,那么该标记不应该被阻止

解决方法:

使用remove方法

如果浏览器允许您将诸如table之类的块元素放在p中,这将起作用:

var p_el = $("<p>testing<table><tr><td>cell 1</td></tr></table> a table</p>")
# Note: This gets slit into 3 elements: p, table, p. This would not
#       happen with a table inside a block element like a `div`

# Find all table elements and remove them:
p_el.find('table').remove()

# If you want the string back you can do:
p_el[0].outerHTML  # p_el[0] gets the DOM object from the jQuery object

# If the string has already been rendered, then of course you should use the 
# appropriate selector to find the `table` elements within `p` elements and then remove them:
$('.someParentEl p table').remove()

# If you need to remove multiple types of elements, then a more elaborate
# selector can be used within remove. I recommend reading up on jQuery selectors
# But an example might be to exclude div tags as well:
$('.someParentEl p').find('table, div').remove()

# What I SUSPECT is that you actually want to remove all block elements from the string
# (table, div, etc. leaving b, i, strong, span, etc.):
$('.someParentEl p *').filter(function(index) {return $(this).css("display") === 'block'}).remove()
# Note: This will only work on elements already in the DOM.

相关:Why is <table> not allowed inside <p>
并且:Nesting block level elements inside the <p> tag… right or wrong?

如果你确实正在处理DOM中段落内的表格,那么这就是另一种蠕虫病毒,而且我不确定如何在客户端持续清理那些混乱.

如果p在你的例子中只是一个不幸的选择,那么我的所有例子都应该与p替换.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐