2011-03-11 73 views
0

我想用.load()函数加载一些内容,这里是我的代码。jQuery变量问题

$(window).load(function() { 

    $('.spotlight').append('<div class="caption"></div>'); 
    $('.spotlight .caption').hover(function() { 
     $(this).animate({ top : '-=50px' }, 150)}, function() { 
     $(this).animate({ top : '+=50px' }, 150)} 
    ); 

    $('.caption').load($(this).parent().data('who')+'.html'); 

}); 

但在HTML我有

<div class="spotlight" who="student"> 
     <img src="sga_small.jpg" /> 
</div> 


<div class="spotlight" who="staff"> 
    <img src="sga_small.jpg" /> 
</div> 

但它试图在undefined.html加载。我将如何去解决这个问题? 这里到页面的链接http://www.coralspringshigh.org/demo/

+0

你能不能给我们,您拨打电话'.load()'整个事件?它很难知道什么'this'没有该函数的上下文... – gnarf 2011-03-11 05:40:08

+1

你可以粘贴完整的HTML与元素有标题类 – 2011-03-11 05:41:20

+0

对不起,添加了其余的代码。 – Koalatea 2011-03-11 05:53:57

回答

0

首先想到的,你应该用data-who="student",而不是仅仅who,这样你可以使用$(this).parent().data('who')+'.html'

现在你已经更新,以包括更多的代码,缺陷更加明显。在这种情况下,this实际上是window,因为您位于$(window).load()处理程序的内部。试着做这样的事情,而不是:

// fires on document ready, not quite window load, but better: 
$(function() { 
    $('.spotlight').each(function() { 
    var spot = $(this), 
     caption = $("<div class='caption'></div>").appendTo(spot); 

    caption.load(spot.data('who') + '.html'); 
    spot.hover(function() { 
     caption.animate({ top : '-=50px' }, 150) 
    }, function() { 
     caption.animate({ top : '+=50px' }, 150) 
    }); 
    }); 
}); 
+1

另外我不认为'谁'属性是有效的任何元素。数据 - {这里任何东西}都是。 – nzifnab 2011-03-11 05:48:18

+0

仍然给出同样的问题 – Koalatea 2011-03-11 05:49:47

+0

@Koalatea - 你需要给我们更多的信息在原来的问题 - 请参阅评论.... – gnarf 2011-03-11 05:51:46

0

可能这是返回undefined:

$(this).parent().attr('who') 

确保该家长在属性谁的值。

+0

它确实,但是这两个父母的属性谁,使其未定义 – Koalatea 2011-03-11 05:49:00

0

试试这个:

$('.caption').each(function() { 
         $(this).load($(this).parent().attr('who') + '.html'); 
        }); 
+0

问题在于它同时加载了两个.captions文件 – Koalatea 2011-03-11 05:48:35

+0

同样的问题仍然存在:\ – Koalatea 2011-03-11 06:17:44