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

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

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


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

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

查询:

  1. $('tr').on({
  2. 'mouseover' : function () {
  3. $(this).closest('tr').find('td').filter(function () {
  4. var $childElems = $(this).children();
  5. // I can see the <a class="remove"> in .children()
  6. // But for some reason can't just test (hey there's an <a>,
  7. // then don't apply this)
  8. if ($childElems.find('a').length <= 0) {
  9. return $(this).css('text-decoration', 'line-through');
  10. }
  11. });
  12. },
  13. 'mouseout' : function () {
  14. $(this).closest('tr').find('td')
  15. .css('text-decoration', 'none');
  16. }
  17. }, 'a.remove');
u3r8eeie

u3r8eeie1#

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

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

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

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

baubqpgj2#

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

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

ecfdbz9o3#

  1. $('tr').on({
  2. 'mouseover' : function () {
  3. $(this).closest('tr').find('td').each(function () {
  4. if($(this).find('a.remove').length == 0){
  5. $(this).css('text-decoration', 'line-through');
  6. }
  7. });
  8. },
  9. 'mouseout' : function () {
  10. $(this).closest('tr').find('td').css('text-decoration', 'none');
  11. }
  12. }, 'a.remove');
qfe3c7zg

qfe3c7zg4#

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

相关问题