如何在jquery中做回调,当获得attr href

How to do callback in jquery, when getting attr href?

本文关键字:attr href 回调 jquery      更新时间:2023-09-26

我有这样的代码:

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

这给我一个链接,但我想有一个回调,使链接被收集,例如:

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

我试过了,但它不工作,我不确定如果我必须传递参数回调。由于

获取属性的值不是异步操作,因为信息在DOM中,您可以直接获取它。你不需要使用回调。

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

当不能立即执行操作时,需要使用回调。例如,当HTTP请求得到响应时,当用户点击链接时,或者当setTimeout达到0时。

可以很简单地这样做

// 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>