jQuery $(this).find 不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5028605/
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-26 18:24:38  来源:igfitidea点击:

jQuery $(this).find not working

jqueryjquery-selectors

提问by theorise

I am making an accordion with a long list of articles.

我正在制作带有一长串文章的手风琴。

I have the jQuery working when I use the following, only it will slideUp/Down every article on the page:

当我使用以下内容时,我让 jQuery 工作,只有它会向上/向下滑动页面上的每篇文章:

$('article a').click(function() {
    $('article').find('h3').slideToggle('fast');
});

In theory this should work, but it doesn't do a thing:

理论上这应该有效,但它没有做任何事情:

$('article a').click(function() {
    $(this).find('h3').slideToggle('fast');
});

You can see a demo here: http://jsfiddle.net/CfqGG/

你可以在这里看到一个演示:http: //jsfiddle.net/CfqGG/

Where am I going wrong?

我哪里错了?

回答by BoltClock

In theory that should notwork because in your click event, thisrefers to the <a>, not the <article>, because your click event is bound to <a>.

从理论上讲应该没有工作,因为在点击事件,this指的是<a>,不是<article>,因为你的点击事件势必<a>

Try this:

尝试这个:

$('article a').click(function() {
    $(this).parent().find('h3').slideToggle('fast');
});

回答by Gidon

$(this).siblings('h3').slideToggle('fast');

thisrefers to the aelement, and findsearches an element in its descendants. h3is not a descendant but a sibling.

this引用该a元素,并find在其descendants. h3不是后代而是兄弟姐妹。

回答by Sarfraz

You need this:

你需要这个:

$('article a').click(function() {
    $(this).closest('article').find('h3').slideToggle('fast');
});

Check out the DEMO

查看演示

回答by TNC

In your code, $('article a')and subsequently $(this)is looking inside of the anchor.

在您的代码中,$('article a')随后$(this)正在查看锚点内部。

回答by user2514927

Here is the updates code, check it out, you need specify the its sibling, cheers

这是更新代码,检查出来,你需要指定它的兄弟,干杯

$(document).ready(function() {    
    //hides articles
    $('article h3').hide();  
    //article accordian
    $('article a').click(function() {
        $(this).siblings('h3').slideToggle('fast');
    });
});