2013-02-28 43 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