How can I reduce the amount of children I use in my jQuery functions?

ε祈祈猫儿з 提交于 2019-12-03 04:25:32

问题


I feel like I have to use way too many .children() in some of my jQuery functions.

Here's my HTML:

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

And here's my 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"});
});

Is there a better way? How can I reduce the amount of children I use in my jQuery functions?


回答1:


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

or more simply:

.find('.goal-action').whatever()



回答2:


have you heard about .find() ?

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



回答3:


Instead of

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

You can use:

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

For exactly the same meaning. If there's no chance of that being ambiguous, however, (.goal-actions will only appear in that structure of the markup) you can just use find('.goal-actions').




回答4:


You can just use:

$('.goal-small-container').hover(function() {
   $(this).find('goal-actions').show();
}, function() {
   $(this).find('goal-actions').hide();
});



回答5:


Why don't you just use .show() and .hide() on the second <div>? And, initially have them display hidden or something.



来源:https://stackoverflow.com/questions/3852260/how-can-i-reduce-the-amount-of-children-i-use-in-my-jquery-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!