-1

我有这个代码:

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

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

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

我试过了,但它不起作用,我不确定我是否必须将参数传递给回调。谢谢

4

2 回答 2

6

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

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

当您无法立即执行操作时,您需要使用回调。例如,当 HTTP 请求得到响应时,当用户单击链接时或当 asetTimeout达到 0 时。

于 2013-02-28T22:24:25.170 回答
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>
于 2013-02-28T22:28:57.747 回答