【问题标题】:.find replacing content inside html tags.find 替换 html 标签内的内容
【发布时间】:2012-10-20 00:57:09
【问题描述】:

我想清理我所见即所得的 html 标签。我想用另一个替换某些标签。这几乎只适用于 replaceWith() 也从标签中删除内容。我不想这样做。我只想更换标签。这是我目前所拥有的。

测试文本:

This<div>is</div><div>a test</div><div>to clean&nbsp;</div><div>some tags</div><div><br></div>

预期结果:

This<p>is</p><p>a test</p><p>to clean</p><p>some tags</p><p><br></p>

实际结果:

This<p></p><p></p><p></p><p></p><p></p>

这是我用来查找和替换的代码

var thebad = ["h1","h2","h3","h4","h5","h6","div"];
        var thegood = ["","","","","","","<p>"];
        for(var i = 0; i < thebad.length; i++){
            $('.content').contents().find('body').find(thebad[i]).replaceWith(thegood[i]);
        }

当我替换它们时,我需要弄清楚如何将文本保留在 html 标签内。

提前致谢

【问题讨论】:

  • 你忘记了“丑”:&lt;script&gt;:D(开个玩笑)
  • 只是指出它会从任何上述标签中删除文本,例如

    Test

    会导致空值,因为它也会删除单词“Test” .

标签: jquery


【解决方案1】:

试试这个:

$('div').contents().unwrap().wrap('<p />'); 

编辑:

$('div').replaceWith(function(){ 
    return $("<p />").append($(this).contents()); 
});

【讨论】:

  • 感谢回复,结果为空
  • 输出相同的结果This

  • 感谢您的回复和努力!
【解决方案2】:

试试这个:

var text = $("#test").html();
var replace_tags = { "<div>": "<p>", "</div>": "</p>",  "<div ": "<p "}; //edited
$.each( replace_tags, function(i,v){
     text = text.replace(new RegExp(i, 'g'),v);
});
//console.log(text);

测试日期:

<div id='test'>
    <h1>dummy text</h1>
    <div>dummy text</div>
    <h1>dummy text</h1>
    <p>dummy text</p>
    <div>dummy text</div>
</div>

结果:

<h1>sadsad</h1>
<p>sadsad</p>
<h1>fsdfsd</h1>
<p>dasdasdasdsad</p>
<p>sadsad</p>

【讨论】:

  • 如果一个 div 有一个样式或类,它也可以被替换吗?例如
    ok
    导致
    ok

  • var replace_tags = { "
    ": "

    ", "

    ": "", "
【解决方案3】:
$("div").replaceWith(function() {
    var $div = $(this);
    return $("<p />")
        //.attr('class', $div.attr('class')) // uncomment if you need to give back same class value
        .html($div.html());
});

【讨论】:

  • 感谢古斯通兹的回复
  • 和?它不工作?这是正确的 jquery 方法。
猜你喜欢
  • 2022-12-08
  • 2013-12-07
  • 2011-11-03
  • 2019-05-27
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 2015-05-01
相关资源
最近更新 更多