JQuery - 查找和替换文本

JQuery - Find and replace text

我正在尝试仅将“产品 Number/Description”的文本替换为“产品编号”。这是代码行:

<td><input type="checkbox" name="dessearch">&nbsp;Product Number/Description</td>

我尝试了以下操作,但它也删除了输入:

$("#ordersearch-page #content table tr td").text(function () {
    return $(this).text().replace("Product Number/Description", "test"); 
});

如有任何帮助,我们将不胜感激!

一个选项是替换 HTML 而不是文本。这将保留 <input> 元素。

$("#ordersearch-page #content table tr td").html(function(i, oldhtml) {
  return oldhtml.replace("Product Number/Description", "test");
});

但是,这也会丢失对 <input> 元素的任何动态更改,例如用户输入的值或事件侦听器。

另一种选择是将文本放入嵌套元素中,以便您可以专门针对它。

$("#ordersearch-page #content table tr td span").text(function(i, oldtext) {
  return oldtext.replace("Product Number/Description", "test");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ordersearch-page">
  <div id="content">
    <table>
      <tr>
        <td><input type="checkbox " name="dessearch "><span>&nbsp;Product Number/Description</span></td>
      </tr>
    </table>
  </div>
</div>

为此,您可以使用 contents() 方法检索特定文本节点,并更新其 nodeValue,如下所示:

$("table tr td").each((i, el) => {
  let node = $(el).contents().filter((i, n) => n.nodeType === Node.TEXT_NODE && n.nodeValue.trim() !== '')[0];
  node.nodeValue = node.nodeValue.replace("Product Number/Description", "test");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="checkbox" name="dessearch">&nbsp;Foo</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="dessearch">&nbsp;Product Number/Description</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="dessearch">&nbsp;Bar</td>
  </tr>
</table>