Живая функция jQuery с setTimeout - PullRequest
1 голос
/ 01 ноября 2011

Я пытаюсь объединить функции mouseenter, live и setTimeout для создания анимации

$(".kundenList li").live("mouseenter", function(){
    if ($(this).children().length > 0) {
        $(this).data('timeout', setTimeout( function () {
            $(this).children("div.description").css({opacity: '0'});

            $(this).children("div.blacklayer").animate({
                opacity: '0.85'
            }, 300);

            $(this).children("div.description").animate({
                top: "-=200px",
                opacity: '1'
            }, 300).css( 'cursor', 'pointer' );

            $(this).addClass("activeLI");
        }, 300));
    }
});

HTML выглядит так

<ul class="kundenList">
    <li>
        <img src="t3.png" class="kundenImg" />
        <div class="blacklayer" style="opacity: 0;"></div>
        <div class="description">
            <h3>Title</h3>
            <p>Description</p>
        </div>
    </li>
</ul>

Поскольку я, очевидно, публикую скрипт вопросане работает :).Кто-нибудь знает почему?Спасибо.

PS Мне нужна живая функция, так как я загружаю новый контент через ajax

Ответы [ 2 ]

3 голосов
/ 01 ноября 2011

this внутри setTimeout относится к глобальному window объекту. Сохраните ссылку на this во временной переменной, как показано ниже. Скрипка: http://jsfiddle.net/de7Fg/

$(".kundenList li").live("mouseenter", function(){
    var $this = $(this); //Reference to `$(this)`

    if ($this.children().length > 0) {
        $this.data('timeout', setTimeout( function () {
            // $this points to $(this), as defined previously
            $this.children("div.description").css({opacity: '0'});

            $this.children("div.blacklayer").animate({
                opacity: '0.85'
            }, 300);

            $this.children("div.description").animate({
                top: "-=200px",
                opacity: '1'
            }, 300).css( 'cursor', 'pointer' );

            $this.addClass("activeLI");
        }, 300));
    }
});
2 голосов
/ 01 ноября 2011

Вы не можете получить доступ к li с помощью this внутри тайм-аута.Перед функцией тайм-аута определите переменную, присвоив ей $(this), и используйте ее в такой функции ( пример ):

$(".kundenList li").live("mouseenter", function(){
    var $this = $(this);
    if ($this.children().size() > 0) {

        $this.data('timeout', setTimeout( function () {
            $this.children("div.description").css({opacity: '0'});

            $this.children("div.blacklayer").animate({
                opacity: '0.85'
            }, 300);

            $this.children("div.description").animate({
                top: "-=200px",
                opacity: '1'
            }, 300).css( 'cursor', 'pointer' );

            $this.addClass("activeLI");
        }, 300));
    }
});
...