使用 jQuery 在所有 div 元素中进行文本查找和替换是一种常见的 DOM 操作,它允许开发者批量修改网页内容而无需手动逐个修改。
$(document).ready(function() {
// 查找所有div元素
$('div').each(function() {
// 获取当前div的文本内容
var text = $(this).text();
// 执行替换操作(例如将"旧文本"替换为"新文本")
var newText = text.replace(/旧文本/g, '新文本');
// 将修改后的文本设置回div
$(this).text(newText);
});
});
$(document).ready(function() {
$('div').each(function() {
var html = $(this).html();
var newHtml = html.replace(/旧文本/g, '新文本');
$(this).html(newHtml);
});
});
/旧文本/gi
中的 i
标志。$(document).ready(function() {
$('div').each(function() {
$(this).html(function(i, html) {
return html.replace(/旧文本/g, function(match) {
return '<span class="highlight">' + match + '</span>';
});
});
});
});
问题:替换不起作用
问题:替换后格式丢失
没有搜到相关的文章