18

我觉得我必须在我的一些 jQuery 函数中使用太多.children()

这是我的 HTML:

<div class="goal-small-container">
  <div class="goal-content">
    <div class="goal-row">
      <span class="goal-actions">

这是我的 jQuery:

$('.goal-small-container').hover(function() {
  $(this).children('.goal-content').children('.goal-row').children('.goal-actions').css({visibility: "visible"});
}, function () {
  $(this).children('.goal-content').children('.goal-row').children('.goal-actions').css({visibility: "hidden"});
});

有没有更好的办法?如何减少我在 jQuery 函数中使用的子项数量?

4

5 回答 5

27
.find('.goal-content .goal-row .goal-action').whatever()

或更简单地说:

.find('.goal-action').whatever()
于 2010-10-04T01:13:53.220 回答
14

你听说过.find()吗?

$('.goal-small-container').hover(function() {
  $(this).find('.goal-actions').css({visibility: "visible"});
}, function () {
  $(this).find('.goal-actions').css({visibility: "hidden"});
});
于 2010-10-04T01:13:41.557 回答
9

代替

$(this).children('.goal-content').children('.goal-row').children('.goal-actions').css({visibility: "visible"});

您可以使用:

$(this).find('> .goal-content > .goal-row > .goal-actions').css({visibility: "visible"});

为完全相同的意思。但是,如果没有可能产生歧义,(.goal-actions只会出现在标记的该结构中),您可以使用find('.goal-actions').

于 2010-10-04T01:13:50.307 回答
1

您可以使用:

$('.goal-small-container').hover(function() {
   $(this).find('goal-actions').show();
}, function() {
   $(this).find('goal-actions').hide();
});
于 2010-10-04T01:19:30.083 回答
0

你为什么不在第二个上使用 .show() 和 .hide()<div>呢?并且,最初让它们显示隐藏或其他东西。

于 2010-10-04T01:15:11.127 回答