Javascript替换删除HTML [英] Javascript Replace removes HTML

查看:77
本文介绍了Javascript替换删除HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript的字符串替换函数似乎是剥离HTML标签,有没有办法禁用它?

Javascript's string replace function seems to be stripping HTML tags, is there a way to disable this?

示例:

http://jsfiddle.net/TDd7w/


$('#pageEnumeration').text(function(){
    return $(this).text().replace(/^Showing \d+-\d+ of/, 'Showing ');
});



<p id="pageEnumeration">
  Showing 1-25 of 45 records found:
  <br>
  containing the terms:
  <span class="italic">cat</span>
</p>


推荐答案

实际上,它归结为以下事实:你通过.text()访问文本节点,它完全去除了标记。

Actually, what it comes down to is the fact that you're accessing the text node through .text(), which does completely strip out markup.

http://jsfiddle.net/mori57/dkLLX/

这是你在找什么?

$('#pageEnumeration').html(function(i, htm){
    return htm.replace(/^Showing \d+-\d+ of/, 'Showing ');
});

你需要使用.html()方法访问,而不是.text()如果你想保留元素节点。

You need to access using the .html() method, not .text() if you want to preserve element nodes.

这篇关于Javascript替换删除HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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