1

我遇到了一种情况(有点失控),在渲染 HTML 时,调试文本被插入到我的 DOM 中。文本如下所示:

, NameSpace.ClassName, Version=x.x.x.x, Culture=neutral, PublicKeyToken=null 

文本只是内联呈现,而不是在元素中。如果它至少放在 adiv或 a中span,我可以做点什么,但它只是body加载模块的地方的一部分。所以首先我尝试了以下方法:

var goodText = $('body').html();
goodText = goodText.replace(/, Plugin.[a-zA-Z0-9]*, Version=\d\.\d\.\d\.\d, Culture=neutral, PublicKeyToken=null/g, '');
$('body').html(goodText);

虽然这将文本从混合中删除,但它正在替换整个body文档,因此 jQuery 的文档准备就绪再次触发。我的其他脚本开始像北极的小骆驼一样哭泣,页面分崩离析。

页面的典型块如下所示,作为模块的输出:

<div class="row">
  , NameSpace.ClassName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 
  <div> some stuff</div>
  <script> $(function(){ // some script }); </script>
</div>

因此,即使我将目标.row替换为上面的 regex/string.replace 文本并在元素上设置 HTML,该 jQuery 块也会再次执行。说白了就是一大堆胡闹的涂鸦。

另一方面,我正在使用 RazorGenerator 加载模块,以在 Asp.Net MVC4 项目中构建 DLL 和 BoC 的预编译视图。

我还尝试使用自定义 ActionFilterAttribute 的类级实现,但其中没有任何内容可以捕获/覆盖实际生成/渲染此文本的位置。

我在这里有什么选择?我可以用另一种方式清除该文本吗?我可以再次阻止该脚本块的执行吗?我在 ASP.NET 请求管道中是否有任何其他选项可以让我使用该恶魔文本?

4

2 回答 2

2
$("body").contents().filter( function(){
    return this.nodeType === 3 && /Version=\d\.\d\.\d\.\d/.test(this.nodeValue);
}).remove();

编辑:由于看起来文本可能不在正文的正下方,我们需要遍历整个 dom:

function walk( root ) {

    $( root ).contents().each( function() {

        if( this.nodeType === 1 && this.nodeName.toLowerCase() !== "iframe" ) {
            walk( this );
        }
        else if( this.nodeType === 3  && /Version=\d\.\d\.\d\.\d/.test(this.nodeValue)) {
            $(this).remove();
        }
    });
}

walk( "body" );
于 2012-05-30T14:41:03.110 回答
1

这是一个基于@Pointy 建议的工作jsfiddle。根据您的具体细节调整您的正则表达式。

//This is from http://stackoverflow.com/a/4399718/266795
var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").andSelf().contents().filter(function() {
        return this.nodeType == 3;
    });
};

$(function () {
  getTextNodesIn("body").each(function (index, node) {
      if (/.*, NameSpace/.test(node.textContent)) {
         $(node).remove();              
      }
  });
});​
于 2012-05-30T14:44:05.013 回答