jQuery Using .on() with .each()

jQuery Using .on() with .each()

本文关键字:each with Using jQuery on      更新时间:2023-09-26

我正在尝试使任何带有"RW"字符串的TD单元格具有红色类。我需要使用 .on,因为网格具有分页功能并重新加载新内容。我还需要使用每个,因为可能有多个包含字符串的 TD 单元格。

 $("#json-table").on("tbody tr td"){
 if ($(this).text() == 'RW').each({
 $(this).addClass('red'))};
如果您

不担心td中是否存在其他字符,则可以使用:contains选择器更直接地过滤到正确的单元格:

$('#element_id').on('click', function() {
    $('#json-table td:contains("RW")').addClass('red');
});

其中element_id是要分配 click 事件处理程序的元素的 ID。

您需要

使用.filter()来缩小此处的集合范围,但是如果没有更多信息,我们无法说出从哪里调用它。 请记住,jQuery函数在整个集合上运行,这是您想要的:

$("#json-table tbody tr td").filter(function() {
  return $(this).text() == 'RW';
}).addClass('red');

。您需要使用分页代码调用它。

编辑:由于您似乎正在使用 datatables.net,因此更完整的示例是:

$('#json-table').bind('sort filter page', function () {
  $("tbody tr td", this).filter(function() {
    return $(this).text() == 'RW';
  }).addClass('red');
});

.on() 和 .each() 是完全不同的。.on() is used to attach an event 其中 .each() is used to iterate over objects or arrays.

试试这个

$("#json-table tbody tr td").each(function(){
       var $this = $(this);
    if($this.text().indexOf('RW') > -1)){
        $this.addClass('red');
    }|
});
.on用于

处理由元素触发的事件。查看文档以了解正确的用法。假设您要处理单击事件,语法如下所示。您提到事件将被委派,因此您的使用情况必须与此签名匹配。

$("#json-table").on('click', "tbody tr td", function() {
    if ( $(this).text() == 'RW') ) {
        $(this).addClass('red');
    }
});

请注意,按原样,您的.each被链接到 if 语句,该语句无效的 JS。 this已引用您定位的正确<td>元素。