代码之家  ›  专栏  ›  技术社区  ›  Marc

JQuery-查找和替换文本

  •  0
  • Marc  · 技术社区  · 4 年前

    我试图将“产品编号/说明”的文本仅替换为“产品编号”。这是代码行:

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

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

    0 回复  |  直到 4 年前
        1
  •  1
  •   Barmar    4 年前

    一种选择是替换HTML而不是文本。这将保持 <input> 要素

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

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

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

    $("#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>
        2
  •  1
  •   Rory McCrossan Hsm Sharique Hasan    4 年前

    要实现这一点,您可以使用 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>