首页 > 解决方案 > JQuery - 查找和替换文本

问题描述

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

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

任何帮助将不胜感激!

标签: jquerytextreplacefind

解决方案


一种选择是替换 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>


推荐阅读