$(".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>
关于javascript - 如何按行搜索并替换该行的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301395/