首页 > 解决方案 > 如何按行搜索并替换该行的内容

问题描述

小提琴

$(".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 中的文本,但它不起作用......

任何帮助,请...

标签: javascriptjquery

解决方案


工作小提琴

您可以将这些行存储在一个数组变量中(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 &amp; test 959 my info2 &amp; test 1200 my info3 &amp; test 450 my info4 &amp; test 908
</dd>


推荐阅读