jquery .filter()则仅应用于某些.children()

bqucvtff  于 2022-11-03  发布在  jQuery
关注(0)|答案(4)|浏览(124)

我好像搞不懂这个,觉得我错过了什么愚蠢的事情...


基本上,当悬停在 * 删除链接 * 上时,我会尝试对该行中的所有文本执行 * 换行 * 操作,除了其中包含<a class="remove"><td>
基本的html结构是:

<tr>
    <td>Lorem ipsum text here</td>
    <td>01/01/2012</td>
    <!-- all <td>'s except for the Remove one should get a line-through -->
    <td><a class="remove">Remove</a></td>
</tr>

查询:

$('tr').on({
    'mouseover' : function () {
        $(this).closest('tr').find('td').filter(function () {
            var $childElems = $(this).children();

            // I can see the <a class="remove"> in .children()
            // But for some reason can't just test (hey there's an <a>, 
            // then don't apply this)

            if ($childElems.find('a').length <= 0) {
                return $(this).css('text-decoration', 'line-through');
            }
        });
    },
    'mouseout' : function () {
        $(this).closest('tr').find('td')
            .css('text-decoration', 'none');
    }
}, 'a.remove');
u3r8eeie

u3r8eeie1#

filter()中,this依次是td中的每个元素,当你调用children()时,你会得到一个jQuery对象 ,也就是<a>,然后,你会在<a>中搜索 * 另一个 * <a>(这就是为什么你看不到它)。
而应:

$(this).closest('tr').find('td').filter(function () {
        if ($(this).children('a').length == 0) {
            return $(this).css('text-decoration', 'line-through');
        }
    });

......但这并不是filter的真正设计目的。您应该使用filter来减少元素集,然后对结果进行操作:

$(this).closest('tr').find('td').filter(function () {
    return !$(this).children('a').length;
}).css('text-decoration', 'line-through');
baubqpgj

baubqpgj2#

如果您不直接操作CSS属性,而是使用类来操作,这将容易得多。
将该类添加到悬停时的tr元素中,并使用后代选择器格式化td

tr.highlighted td { text-decoration:line-through; }
tr.highlighted td:last-child { text-decoration:none; }
ecfdbz9o

ecfdbz9o3#

$('tr').on({
    'mouseover' : function () {
        $(this).closest('tr').find('td').each(function () {
            if($(this).find('a.remove').length == 0){
                $(this).css('text-decoration', 'line-through');
            }
        });
    },
    'mouseout' : function () {
        $(this).closest('tr').find('td').css('text-decoration', 'none');
    }
}, 'a.remove');
qfe3c7zg

qfe3c7zg4#

$('a.remove').hover(function () {
    $(this).parents('tr').find('td').filter(function () {
        return !$(this).find('a.remove').length;
    }).css('text-decoration', 'line-through');
}, function () {
    $(this).parents('tr').find('td').css('text-decoration', 'none');
});

相关问题