问题
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