javascript - .filter() 然后仅适用于某些 .children()

标签 javascript jquery jquery-events

似乎无法弄清楚这个问题,感觉我在这里错过了一些愚蠢的东西......

<强> jsFiddle Demo

基本上,当悬停删除链接上时,我会尝试对该行中的所有文本进行换行,除了 <td>与此<a class="remove">在里面。

基本的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>

jQuery:

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

最佳答案

filter()内, thistd 中的每一个元素依次。当您调用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');

关于javascript - .filter() 然后仅适用于某些 .children(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15527879/

相关文章:

jquery - 如果正文中的目标不是标签标签,请隐藏某些内容

javascript - 是否可以从继承自 A 的对象调用对象 A 内的 Javascript 函数(私有(private)函数)?

javascript - 如何在 14 秒内向下滚动 jQuery 页面

jquery - 使用 jQuery 标准化 CodeMirror OnKeyEvent

javascript - 如何使用关联数组上的整数索引进行迭代?

javascript 等待 DOM 元素实际绘制并完成

jquery - 将 jQuery 单击事件分配给正文中除少数 div 及其子元素之外的所有内容

javascript - 调整图片大小,需要一个好的库

javascript - 在找到最长的单词之前拆分字符串

javascript - 为什么 div 的宽度不占总宽度的 90%?