2013-02-28 26 views
-1

我有這樣的代碼:如何在獲取attr href時在jQuery中做回調?

$("#downloadPopup").attr("href") 

這給我回一個鏈接,但我希望有一個回調,使該鏈接被收集,例如:

$("#downloadPopup").attr("href", function(){ 
     console.log($(this)); 
     // i need make sure the link value is available (promise). 
    }); 

我試過,但它不工作,即時通訊不知道如果我必須通過參數回調。謝謝

+0

'如果($( 「#downloadPopup」)。attr(「href」)!=「」)'???? – adeneo 2013-02-28 22:22:45

+0

你想追蹤它的變化嗎?或者只是獲取當前值。如果您只想要當前值,則不需要回調。 – 2013-02-28 22:24:13

+0

爲什麼不使用'$(「#downloadPopup」)。attr(「href」)'作爲console.log()的參數? – 2013-02-28 22:24:46

回答

2

這可以很簡單,像這樣

// Here we save a reference to the orginal method 
$.fn._attr = $.fn.attr; 

// We can now define our own version 
$.fn.attr = function (attr, callback) { 

    // Now we test to make sure that the arguments are provided in the way you want 
    if (typeof attr === 'string' && typeof callback === 'function') { 

     // Save the result of the callback 
     var result = callback.call(this, attr); 

     // If the callback returns a valid "value" we assign that as the new attribute 
     if (typeof result === 'string') { 
      return $.fn._attr(attr, result); 
     } 

    } 

    // If the arguments, or return of our function, are not what we expected, we execute the normal method here 
    return $.fn._attr.apply(this, arguments); 

}; 

要使用這個新功能attr我們可以做執行此

// Here prop is the name of the attribute you passed in 
$('div').attr('foo', function (prop) { 
    return prop + 'bar'; 
}); 

這樣做的結果將是

<div foo="foobar"></div> 
+0

但是,爲什麼這樣呢? – jfriend00 2013-02-28 22:31:29

+0

@ jfriend00 - 只是重寫jQuery沒有明顯的原因總是一個好主意,而且它也很有趣! – adeneo 2013-02-28 22:31:59

+0

等待......不.attr已經支持這種語法? – 2013-02-28 22:32:44

6

獲取屬性的值不是異步操作,因爲信息位於DOM中,您可以獲取它。你不需要使用回調。

var pop = $("#downloadPopup") 
var href = pop.attr("href"); 
doSomethingWith(pop, href); 

當您無法立即執行操作時,您需要使用回調。例如當一個HTTP請求得到響應,當鏈接被用戶點擊或者當setTimeout達到0