如何使用 jQuery 替换页面上的文本而不替换标签和标签内的文本,例如:<a>,<input>,<button>,<textarea>,<input>,<select>
.
例如,这里是HTML代码
<html>
<head>
<title>Testing</title>
</head>
<body>
Hello, this is a test replacing {REPLACE_ME} with <b>{REPLACED}</b>.
<br/><br/>
I want {REPLACE_ME} and {REPLACE_ME} to be <b>{REPLACED}</b>, however I don't want this <a href="#">{REPLACE_ME}</a> to become <a href="#">{REPLACED}</a>.
Same with <textarea>{REPLACE_ME}</textarea>, it shouldn't change.
<br/><br/>
</body>
我有这个 jQuery 来替换文本
var replaced = $("body").html().replace(/{REPLACE_ME}/gi,'<b>{REPLACED}</b>');
$("body").html(replaced);
在 JSFiddle 上
最佳答案
$('body, body *:not(a,button,textarea,option)').contents().filter(function() {
return this.nodeType === 3;
}).each(function() {
var escaped = $('<div></div>').text($(this).text()).html();
$(this).replaceWith(escaped.replace(/\{REPLACE_ME\}/gi,'<b>{REPLACED}</b>'));
});
(我不需要包含input
,并且我使用了option
而不是select
,因为option
是带有 child 文本节点的节点。)
关于javascript - 使用 jQuery 有选择地用 HTML 替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20535924/