0

このコードを使用して、ボディ内のすべてのノードのテキストを取得します (ブラウザーは IE8 であり、FF で動作します...)

ありがとう、私はページ内のいくつかのテキストを変更するツールバーを開発しているので、他の解決策があれば私を幸せにします友達の検索セクションで無効になりますので、単語を段階的に変更したい、悪い単語のフィルターです

function replaceText(node)
{
 var textPropName = node.textContent === undefined ? 'innerText' : 'textContent';
 var childs = node.childNodes, i = 0;
 while(i < childs.length)    
 {
 alert(childs[i][textPropName]);
   if (childs[i][textPropName] !=null)
    {
      childs[i][textPropName] =childs[i][textPropName].replace(rgx,'new');
    }
    else
    {
      replaceText(document.body.childNodes[i]);} i++; 
    }
 }
}

それは機能し、ページ上のすべてのテキストを置き換えることができますが、テキストがbeloveと同じタグの外にある場合、それにアクセスして置き換えることができません
問題: test5 ww tt xxテストはどのタグにも含まれていないため、解決策は置き換えられません? 心から

ww tt ff xx test5 test
<b>
test old old  yyyl  yyy ppp  
  <h2> ppp gfdsgfds gf dg df   yyy old odld old</h2>
</b>
  <h1 id="myHeader" onClick="replaceText(document.body)"> 
     yyy   yyy  yyy  yyy   old Click me! whatever
 </h1>
ppp  ppp ppp bwhoreface 
<b> 
ppp

エンドソリューション

function replaceText(node){ 
var textPropName = node.textContent === undefined ? 'innerText' : 'textContent';
   var childs = node.childNodes, i = 0;
var len= node.childNodes.length;
// alert('len='+len);
//var rgx = new RegExp('\\bold\\b', 'gi');
   while(node = childs[i]){
//alert('ee'+node.nodeType);  
if (node.nodeType == 3  ) {
//alert('!!!!!'+node.nodeValue );
//alert('ee'+node.nodeType); 
childs[i].nodeValue = childs[i].nodeValue.replace(rgx, 'newText'); 
} else { 
   replaceText(node); 

}
4

2 に答える 2

0

content()プロパティを使用します:- テキスト ノードとコメント ノードを含む、一致した要素のセット内の各要素の子を取得します。

これを試して:

// in jquery
$("body").contents().filter(function() {
  return this.nodeType == 3;
}).replaceWith("hello");


// in javascript
var nodes = document.getElementsByName('body').childNodes
for (i=0; i < nodes.length; i++)
{
 if(nodes.childNode[i].nodeType == 3)
 {
 //THIS NODE IS A TEXT NODE OF THE BODY ELEMENT
 //DO WHAT YOU NEED WITH IT
 }
}

ここを参照リンク

于 2013-01-27T18:08:55.180 に答える
0

ほら、これはIEでも動作します...

ライブデモ

function replaceText(node)
{
    var textPropName = node.textContent === undefined ? 'innerText' : 'textContent';
    var childs = node.childNodes, i = 0;
    var rgx = new RegExp('\\bff\\b|\\byyy\\b', 'gi');

    while(i < childs.length)    
    {
        if(childs[i].nodeType == 3) {
            alert(childs[i].nodeValue);

            childs[i].nodeValue = childs[i].nodeValue.replace(rgx,'new');
        } else {
            alert(childs[i][textPropName]);

            if (childs[i][textPropName] !=null)
            {
                childs[i][textPropName] =childs[i][textPropName].replace(rgx,'new');
            }
            else
            {
                replaceText(document.body.childNodes[i]);
            } 
        }

        i++; 
    }
}
于 2013-01-27T17:44:45.480 に答える