0

我一直在试图弄清楚这一点。我正在尝试使用 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/

4

3 回答 3

3
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!" );
于 2013-05-27T19:34:05.133 回答
2
$("td").filter(function(){
 return $.trim($(this).text()) == 'Value 1';
}).text("Value 1.TO THE MAX");

演示---> 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");

演示---> http://jsfiddle.net/9gBqU/27/

于 2013-05-27T19:30:44.087 回答
1

jsFiddle Demo

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

$("td").each(function(){
 if($(this).text().trim() == "Value 1"){
  $(this).text("Value 1.TO THE MAX");   
 }
});
于 2013-05-27T19:33:20.240 回答