javascript - 如何按行搜索并替换该行的内容
问题描述
$(".my-item").each(function() {
var lines = $(this).text().split("\n");
var k = "";
$.each(lines, function(n, elem) {
if (elem.trim().length > 0) {
if (elem.indexOf('my info1 & test') !== -1) {
alert("in here");
debugger;
elem.replace('959', '600');
alert(elem);
}
}
});
});
当我按行搜索并满足条件时,我想替换 DOM 中的文本,但它不起作用......
任何帮助,请...
解决方案
您可以将这些行存储在一个数组变量中(result
在我的示例中),然后在末尾使用新行加入它们,join()
最后在 DOM 中替换它们:
$(this).text(result.join("\n"));
$(".my-item").each(function() {
var lines = $(this).text().split("\n");
var result = [];
$.each(lines, function(n, elem) {
if (elem.trim().length > 0) {
if (elem.indexOf('my info1 & test') !== -1) {
elem = elem.replace('959', '600');
}
}
result.push(elem);
});
$(this).text(result.join("\n"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dd class="my-item" style="height: 44px;">
my info1 & test 959 my info2 & test 1200 my info3 & test 450 my info4 & test 908
</dd>
推荐阅读
- vba - VBA 选项按钮真、假或空
- xml - Ironpython 使用 xmlns 读取 XML
- c# - Nancy Autofac 防止容器处置
- gremlin - Gremlin Python 如何使 by(values('name','score')) 工作
- mcmc - 运行 Jags - 从 mcmc 对象中提取多个实现
- java - JavaFX TreeTableView 图像伪影
- java - 我尝试将 Spring 的默认记录器更改为 log4j2 有什么问题?
- r-markdown - 使用脉轮选项后,Blogdown/Xaringan 不起作用
- javascript - 使用 fetch 将文件和数据发送到服务器
- mysql - 根据特定列值连接两个表