这几乎替换了页面的HTML代码,但不影响标签和代码,只影响显示给用户的文本。
例如,我想替换此页面中的所有文本:
<!DOCTYPE html>
<html>
<body>
<ul class="topnav">
<li>Item 1</li>
<li>Item 2
<ul><li>Nested item 1</li><li>Nested item 2</li><li>Nested item 3</li></ul>
</li>
<li>Item 3</li>
</ul>
<div>DIV1</div>
<div>DIV2</div>
<span>SPAN</span>
<table>
<tr>
<td>Username</td>
</tr>
<tr>
<td>Password</td>
</tr>
</table>
<p>
<input type="checkbox" name="remember" tabindex=3 />
<label for="checkbox">Remember <strong>password</strong></label>
</p>
<p>Click here to <a href='register.php'>Register</a></p>
</body>
</html>
结果应该是:
<!DOCTYPE html>
<html>
<body>
<ul class="topnav">
<li>@@@@</li>
<li>@@@@
<ul><li>@@@@</li><li>@@@@</li><li>@@@@</li></ul>
</li>
<li>@@@@</li>
</ul>
<div>@@@@</div>
<div>@@@@</div>
<span>@@@@</span>
<table>
<tr>
<td>@@@@</td>
</tr>
<tr>
<td>@@@@</td>
</tr>
</table>
<p>
<input type="checkbox" name="remember" tabindex=3 />
<label for="checkbox">@@@@<strong>@@@@</strong></label>
</p>
<p>@@@@<a href='register.php'>@@@@</a></p>
</body>
</html>
我已经尝试过以下方法:
使用JQuery替换所有仅包含纯文本的元素、标签(及其子标签),这在一开始是可行的:
<ul class="topnav">
<li>@@@@</li>
<li>@@@@
<ul><li>@@@@</li><li>@@@@</li><li>@@@@</li></ul>
</li>
<li>@@@@</li>
</ul>
<div>@@@@</div>
<div>@@@@</div>
<span>@@@@</span>
但最近我意识到,在元素的情况下,如果标签有子元素,它将失败:
<p>
<input type="checkbox" name="remember" tabindex=3 />
<label for="checkbox">Remember <strong>password</strong></label>
</p>
<p>Click here to <a href='register.php'>Register</a></p>
因此,我尝试了另一种方法,使用 document.body.innerText 选择所有文本,但是 HTML 格式丢失了。
我感到很累。有人能帮忙吗?
非常感谢!
body.innerHTML
中在>
和<
之间的任何内容。 - Scott Stevens>
和<
符号,而不是位于同一父级上的开放和关闭标记。 - Scott Stevens<p> hello <strong>world</strong>, now kiss</p>
。根据你的方法,结果是:<p> hello <strong>@@@@</strong>, now kiss</p>
,但我想要的结果是:<p>@@@<strong>@@@</strong>@@@</p>
。我考虑使用正则表达式,但它变得非常复杂。你能找到更有效的方法吗? :-( - Tony Dinh