如何在jquery中做回调,当获得attr href
How to do callback in jquery, when getting attr href?
我有这样的代码:
$("#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>
相关文章:
- .attr(“href”) 的问题!解决此问题的简单方法
- jQuery:使用.attr('href',")调用javascript
- 将URL路径与<a>attr('href')来动态更新.active类
- 为什么jQuery attr('href','#')设置了一个空值而不是#
- 使用 Url.Action 和 jquery href attr 生成链接
- jQuery 无法访问元素及其 attr href // 简单的选项卡结构
- 使用锚点 .attr href 作为计数器中数组的起点
- 如何在 jquery attr() 方法中使用 “javascript:window.location.href” 的
- window.location.href 或 $(location).attr('href') 和波兰语
- Knockout JS href attr 未绑定在 .NET MVC4 部分页面上
- IE8 中的 jQuery Change attr href 会更改文本
- 从ajax动态加载导航中移除Attr(href)
- jQuery attr("href")不起作用
- $(this).attr("href")返回未定义
- Knockout JS模板attr href绑定返回函数而不是值
- this.href vs $(this).attr('href')
- 如何在jquery中做回调,当获得attr href
- jQuery对象".attr('href')"返回未定义
- .attr("href")返回未定义
- jquery $(this).attr('href') returns undefined