简体   繁体   English

如何按行搜索并替换该行的内容

[英]How to search by line and replace content for that line

Fiddle 小提琴

$(".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);
      }
    }
  });
});

As I am searching by line and the condition is met, I would like to replace the text in the DOM but it's not working... 当我按行搜索并且满足条件时,我想替换DOM中的文本,但是它不起作用...

Any help, please... 任何帮助,请...

Working fiddle . 工作提琴

You could store the lines in an array variable ( result in my example) then join them at the end with the new line using join() and finally replace them in the DOM : 您可以将这些行存储在数组变量中(在我的示例中为result ),然后使用join()将它们与新行最后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 &amp; test 959 my info2 &amp; test 1200 my info3 &amp; test 450 my info4 &amp; test 908 </dd> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM