Javascript 如何使用 JQuery 仅显示 div 的子元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5251043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:21:55  来源:igfitidea点击:

How to use JQuery to show a div's child elements only?

javascriptjqueryhtmlcssjquery-selectors

提问by raeq

So I have this jquery function that's supposed to show a class's hidden span on hover. How do i set up the function so it only shows the selected div's child span (instead of showing all the spans on the page)?

所以我有这个 jquery 函数,它应该在悬停时显示一个类的隐藏跨度。如何设置该函数,使其仅显示所选 div 的子跨度(而不是显示页面上的所有跨度)?

Here's my jquery function:

这是我的 jquery 函数:

$(".thumb").hover(
    function() {
       $(".blurb").show();
    },
    function(){
       $(".blurb").hide();
    }
);

You can view the jsfidde here. Thanks!

您可以在此处查看jsfidde。谢谢!

回答by Intelekshual

That's what thisis for!

this是为了什么!

$(".thumb").hover(
    function() {
       $(this).children('.blurb').show();
    },
    function(){
       $(this).children('.blurb').hide();
    }
);

回答by Andy E

Use $(this).children()instead of executing a global query again:

使用$(this).children()而不是再次执行全局查询:

$(".thumb").hover(function() {
    $(this).children().show();
}, function() {
    $(this).children().hide();
});

Working demo: http://jsfiddle.net/h5x3f/2/

工作演示:http: //jsfiddle.net/h5x3f/2/

Note: if you're not bothered about supporting Internet Explorer 6, you can avoid jQuery/JavaScript completely and use CSS's :hoverpseudo-class, which will even work with JS disabled. Or you could use a shim like ie-7.jsto handle :hoverfor you. See this variation of your fiddlefor an example.

注意:如果你不介意支持 Internet Explorer 6,你可以完全避免 jQuery/JavaScript 并使用 CSS 的:hover伪类,它甚至可以在禁用 JS 的情况下工作。或者你可以使用像ie-7.js这样的垫片来:hover为你处理。有关示例,请参阅小提琴的这种变体

回答by lindsten

Select the div first and then its children, e.g.

首先选择 div 然后选择它的孩子,例如

$("#mydiv").children(".blurb").show();

回答by vmolero

here you have another solution using the 'find' function:

在这里,您有另一个使用“查找”功能的解决方案:

    $(".thumb").hover(
        function() {
            $(this).find(".blurb").show();
        }, function() {
            $(this).find(".blurb").hide();
        }

    );