2017-10-04 68 views
1

Wow ..獲得關於'this'的真實信息是不是容易,因爲谷歌基本上忽略了這個詞。在嵌套函數中使用'this'

該代碼使用縮略圖中的信息打開數據庫中的圖像.. onlick的作品和懸停代碼的作品,但我不知道如何從mouseenter獲得'this'以用於showModal函數。

 function showModal() { 
     $("body").css("overflow-y", "hidden"); 
     $(".small").removeClass("smallHover"); 
     $(".modal").fadeIn(200); 

     var altLong = $(this).attr("alt"); 
     var altSplit = altLong.split("#"); 
     $(".picTitle").text(altSplit[0]);           
     var srclong = $(this).attr("src"); 
     var srcshort = srclong.split("_"); 
     var srcextension = srclong.split(".");  
     $(".big").attr("src", srcshort[0]+'.'+srcextension[1]); 
    } 
    $(".small").click(showModal); 

    var timer; 
    $(".small").mouseenter(function() { 
     timer = setTimeout(function(){ 
      $(this).showModal(); // **<--this is the line that doesnt work** 
     }, 2000); 
    }).mouseleave(function() { 
     clearTimeout(timer); 
    }); 

此外,如果你能解釋一下爲什麼要使用$(這)是一個jQuery對象,而不是僅僅「這個」以及它們如何不同,那將是巨大的。在此先感謝〜!

回答

3

這有兩個獨立的方面。

  1. 獲得正確的thissetTimeout回調

  2. 調用showModalthis

#1由this question's answers解決。你有幾個選擇,在這種情況下,最簡單的(現在)很可能是使用一個變量:

$(".small").mouseenter(function() { 
    var _this = this; // *** 
    timer = setTimeout(function(){ 
     $(_this).showModal(); // *** 
    }, 2000); 
}).mouseleave(function() { 
    clearTimeout(timer); 
}); 

...但是,代碼仍然是行不通的,因爲showModal不是jQuery的對象的屬性,這是一個獨立的功能。與特定this調用它,你會使用Function.prototype.call

$(".small").mouseenter(function() { 
    var _this = this; 
    timer = setTimeout(function(){ 
     showModal.call(_this); // *** 
    }, 2000); 
}).mouseleave(function() { 
    clearTimeout(timer); 
}); 

(或者,改變showModal接受元素作爲參數,然後只是把它作爲參數傳遞。)

更多thisthis question's answers as well,以及this (old) post on my anemic little blog

+1

另外這個問題回答有助於整個問題OP正經歷:HTTPS: //sackoverflow.com/questions/5889237/jquery-nested-this-references –

+1

Hooray!非常感謝你,我試着把它變成一個變量,然後用電話,但不是在一起。另外感謝您閱讀關於'this'的額外閱讀,它幫助我理解了爲什麼我的其他一些嘗試也無法正常工作(特別是試圖訪問屬性而不是在參考上執行函數) –

0

這也將工作,如果你可以改變你的showModel功能是這樣的:

$.fn.showModal = function() { 
     $("body").css("overflow-y", "hidden"); 
     $(".small").removeClass("smallHover"); 
     $(".modal").fadeIn(200); 
     ... 
    } 

和定時器方法內部

$(this).showModal();