在循环中使用`this`来定位当前项

时间:2012-09-11 17:52:20

标签: javascript jquery

我已经根据我的问题设置了这个jsfiddle:http://jsfiddle.net/7MjN6/

如您所见,我有两张图片。我希望每个div周围的div都会在每次点击时展开。我正在尝试使用this对象来确保单击图像只会扩展该图像的div,但我确定我使用this错误,因为它没有连接。如果有人可以捅我的小提琴,我将不胜感激!

HTML:

<body>
    <div class="img-container">
        <a href="#"><img src="http://blueantlabs.com/wp-content/themes/blueantplate/img/port-wide/thefutureproject-605.png" /></a>
    </div>
    <div class="img-container">
        <a href="#"><img src="http://blueantlabs.com/wp-content/themes/blueantplate/img/port-wide/thefutureproject-605.png" /></a>
    </div>
</body>​

JS:

$(function(){
    $('.img-container').each(function(index){
        var imgHeight = $(" a img").height();
        $('a').click(function(e){
            e.preventDefault;
            $('div').animate({height: imgHeight});
        });
    });     
});​

2 个答案:

答案 0 :(得分:3)

尝试这种方法。您根本不需要.each

$(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
        });
    });
});​

http://jsfiddle.net/mblase75/7MjN6/4/

答案 1 :(得分:0)

您需要将$("div").animate(...)更改为$(this).closest("div").animate(...)。在事件处理程序this内引用单击的链接。您不希望扩展所有div(您当前版本所做的);你想扩展包裹点击链接的div。您可以使用.closest()导航到该页面。