2013-03-20 62 views
2

似乎无法弄清楚这一个,觉得我失去了一些东西愚蠢这里....filter(),那么仅适用于特定的。孩子()

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

回答

3

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'); 
+0

啊没用过'.filter()'很多,应该是我想这一切都是错的!感谢马特,马上清理它。 – 2013-03-20 15:59:52

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

这将是一个更容易,如果你没有直接操纵CSS属性,但使用的类为了那个原因。

该类添加到悬停你tr元素,并使用后代选择格式化td

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

+1绝对是一个好主意,不幸的是我们的主要用户是IE7&8,被迫将JS用于最愚蠢的情况haha – 2013-03-20 15:58:59

+1

我不是说用':hover'来做,而是把类应用到'tr'元素与jQuery。如果':last-child'是你最关心的问题 - 如果最后一个'td'在HTML代码中也有一个类,就可以避免这个问题。 – CBroe 2013-03-20 16:05:29

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

jsFiddle example