2013-03-20 63 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