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

标签 javascript jquery html

我有表格,我想根据类名过滤所有 td 值,然后如果 td 包含特定文本,则将其替换为新文本。下面是我当前的代码。它无法正常工作并更新所有 td 的 . 请建议如何进行。

html

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

j查询

$("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"); 

                }

            });  

最佳答案

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

//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');

关于javascript - jQuery 使用类名查找 td 并根据值更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42888291/

相关文章:

javascript - 获取节点的内部文本

javascript - 如何将变量从一个脚本传递到另一个脚本

jquery - 在页面加载时运行 css div 转换

php - 从地址字段创建动态谷歌地图链接

php - 使用 css 定位 div 标签

html - 放大时元素变大

javascript - 为什么 date.valueOf() == date 会导致 false?

javascript - passportjs 本地策略没有被调用

javascript - 如何在不禁用其子 DOM 对象上的单击事件的情况下禁用父 DOM 对象上的单击事件?

javascript - 如何使用 ajax 填充选择表单?