开发者

jQuery variable trouble

开发者 https://www.devze.com 2023-02-15 23:47 出处:网络
I\'m trying to load in some content with the .load() function, here\'s my code. $(window).load(function() {

I'm trying to load in some content with the .load() function, here's my code.

$(window).load(function() {

    $('.spotlight').append('<div class="caption"></div>');
    $('.spotlight .caption').hover(function 开发者_如何学C() { 
         $(this).animate({ top : '-=50px' }, 150)}, function () {
         $(this).animate({ top : '+=50px' }, 150)}
    );

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

});

but in the HTML I have

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


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

But it tries to load in undefined.html. How would I go about fixing this? Here's a link to the page http://www.coralspringshigh.org/demo/


First thought, you should be using data-who="student" instead of just who, that way you can use $(this).parent().data('who')+'.html'

Now that you've updated to include more of the code, the flaw is more obvious. this in that context is actually window because you are inside of the $(window).load() handler. Try doing something like this instead:

// 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)
    });
  });
});


Chances are this is returning undefined:

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

Make sure that this parent has a value in the attribute who.


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消