Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/449.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在循环中使用“this”以指向当前项_Javascript_Jquery - Fatal编程技术网

Javascript 在循环中使用“this”以指向当前项

Javascript 在循环中使用“this”以指向当前项,javascript,jquery,Javascript,Jquery,我已经为我的问题设置了JSFIDLE: 如你所见,我有两张图片。我希望单击每个按钮时,每个按钮周围的div都会展开。我试图使用this对象来确保单击图像只会扩展该图像的div,但我确信我使用的this是错误的,因为它没有连接。如果有人能试试我的小提琴,我将不胜感激 HTML: 您需要将$(“div”).animate(…)更改为$(this).最近的(“div”).animate(…)。在事件处理程序中,此引用单击的链接。您不希望展开所有div(当前版本会这样做);您想展开包装单击链接的div。

我已经为我的问题设置了JSFIDLE:

如你所见,我有两张图片。我希望单击每个按钮时,每个按钮周围的div都会展开。我试图使用
this
对象来确保单击图像只会扩展该图像的div,但我确信我使用的
this
是错误的,因为它没有连接。如果有人能试试我的小提琴,我将不胜感激

HTML:


您需要将
$(“div”).animate(…)
更改为
$(this).最近的(“div”).animate(…)
。在事件处理程序中,此引用单击的链接。您不希望展开所有div(当前版本会这样做);您想展开包装单击链接的div。您可以使用导航到它。

试试这种方法。您根本不需要
。每个

$(function() {
    $('a').click(function(e) {
        var imgHeight = $(this).find('img').height(); // use "this", find the img inside
        e.preventDefault(); // this is a method, must use parentheses
        $(this).parent().animate({ // "this" is the anchor; move up to the parent
            height: imgHeight
        });
    });
});​

您根本没有使用
这个
。我甚至搜索了你的代码,没有出现“this”这个词,这是我的错误,没有链接到最新的fiddle。非常感谢!我有一个后续问题:是否有一种比每次检查div高度更容易的方法进行切换,如这里所示:?在更改之前,使用存储旧值。试一试,如果你需要更多的帮助,请另发一个问题。
$(function(){
    $('.img-container').each(function(index){
        var imgHeight = $(" a img").height();
        $('a').click(function(e){
            e.preventDefault;
            $('div').animate({height: imgHeight});
        });
    });     
});​
$(function() {
    $('a').click(function(e) {
        var imgHeight = $(this).find('img').height(); // use "this", find the img inside
        e.preventDefault(); // this is a method, must use parentheses
        $(this).parent().animate({ // "this" is the anchor; move up to the parent
            height: imgHeight
        });
    });
});​