【问题标题】:Jquery find text and change single cell valueJquery查找文本并更改单个单元格值
【发布时间】:2026-01-05 11:05:01
【问题描述】:

我一直在努力解决这个问题。我正在尝试使用 JQuery 查找具有精确值的单元格,然后更改该精确单元格中的文本,而不会删除表格的其余部分。

这是一个非常简单的 HTML 表格:

<table border='1'>
    <tr>
        <td>
            <table border='1'>
                <tr>
                    <td>
                        Value 1
                    </td>
                    <td>
                        1234
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td>
            <table border='1'>
                <tr>
                    <td>
                        Value 1.1
                    </td>
                    <td>
                        5678
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>

我想找到与“Value 1”完全匹配的单元格,然后将其更改为“Value TO THE MAX”而不更改任何其他单元格(因此它不会意外匹配单元格“Value 1.1”)

我最近的/非崩溃尝试:

$("td:contains('Value 1')").text("Value 1.TO-THE-MAX");

根据我的阅读,我的问题是表格与此搜索匹配,因为表格包含单元格。这是我的 JSFiddle:http://jsfiddle.net/sonoflysander/9gBqU/15

奖励积分:之后我要尝试做什么,我想务实地立即获取下一个单元格(在本例中为值为“1234”的单元格),因此我也可以任意更改它的值。

一如既往,我们非常感谢任何帮助。


根据 gustavohenke 的回答,我抽象了一个函数,我将在此处包含该函数,以供寻找比我的确切场景更通用的东西的人们使用。

function findString(search, element) {
    search = (typeof search === 'RegExp') ? search : new RegExp('^\\s*' + String(search) + '\\s*$');
    element = (typeof element === 'undefined') ? '*' : element;
    var x = $(element).filter(function () {
        return search.test($(this).text());
    });
    return x;
}

方法签名:

findString(search [, element])

search 可以是字符串或正则表达式,element 是可选的。如果未提供,它将搜索整个身体。为了性能,我建议您指定element

更新的 JSFiddle:http://jsfiddle.net/sonoflysander/9gBqU/

【问题讨论】:

标签: jquery html replace html-table


【解决方案1】:
var affected = $("td").filter(function() {
  // You should use regex here because you'll likely to receive whitespaces in the .text() call
  return /^\s*Value 1\s*$/.test( $( this ).text() );
}).text( "Value 1.TO THE MAX" );

// Now you apply what you want to what comes after that <td>s
affected.next().text( "I'm next to an awesome <td> affected by my code!" );

【讨论】:

  • 非常感谢您的帮助!我绝对认为这是最好的答案。我正在更新我的问题以包含您在此处所做的抽象功能。再次感谢!
【解决方案2】:
$("td").filter(function(){
 return $.trim($(this).text()) == 'Value 1';
}).text("Value 1.TO THE MAX");

演示---&gt;http://jsfiddle.net/9gBqU/21/

要访问下一个td,请在上面的代码中使用.next()

$("td").filter(function(){
 return $.trim($(this).text()) == 'Value 1';
}).text("Value 1.TO THE MAX").next('td').text("i am next");

演示---&gt;http://jsfiddle.net/9gBqU/27/

【讨论】:

    【解决方案3】:

    jsFiddle Demo

    搜索文本,然后修剪它,因为空格会给您带来问题,然后将匹配项分配给正确的值

    $("td").each(function(){
     if($(this).text().trim() == "Value 1"){
      $(this).text("Value 1.TO THE MAX");   
     }
    });
    

    【讨论】:

      最近更新 更多