jQuery使用类名查找td并根据值更改文本

时间:2017-03-19 15:18:08

标签: javascript jquery html

我有表,我想根据类名过滤所有td值,然后如果td持有特定文本,则用新文本替换它。下面是我目前的代码。它不能正常工作并更新所有td。 请告知如何继续。

的HTML

 <td class="actionclass">' . $page->action . '</td>

的jquery

$("tbody").find("tr").each(function() { //get all rows in table
    var ratingTdText = $(this).find('td.actionclass').text();
    if ((ratingTdText == "saved block")) {
        this.innerHTML = 'changed';
    }
});

===

更新

              $("tbody tr td.actionclass").each(function() {       
                var ratingTdText = $(this).text();
                console.log(ratingTdText);
                if(($(this).is(':contains("new")')) || ($(this).is(':contains("saved")'))) {
                        (this).text().replace("top", "TopBar"); 
                         (this).text().replace("left", "LeftBar"); 
                          (this).text().replace("bottom", "BottomBar"); 

                }

            });  

2 个答案:

答案 0 :(得分:1)

this引用TR元素而不是TD,更改find()中的选择器,您的代码将有效

$("tbody").find("tr").each(function() { //get all rows in table
    var ratingTd = $(this).find('td.actionclass');//Refers to TD element
    if (ratingTd.text() == "saved block") {
        ratingTd.text('changed');
    }
});

OR

//get all td with actionclass in table
$("tbody tr td.actionclass").each(function() {       
    var ratingTdText = $(this).text();
    if (ratingTdText == "saved block") {
        this.innerHTML = 'changed';
    }
});

您可以使用.filter()

改进代码
//get all td with actionclass in table
$("tbody tr td.actionclass").filter(function() {       
    return $(this).text() == "saved block";
}).text('changed');

答案 1 :(得分:0)

 this.innerHTML = 'changed';

应该是

 ratingTdText.innerHTML = 'changed';

您不应该在this内使用row而不是td