【发布时间】:2015-10-31 14:30:27
【问题描述】:
var t=new Array('title','placeholder','alt');
$.each(t,function(k,v){
alert(typeof $(this).attr(v));//PROBLEM $(this) is not the right object
});
目标: 获取存在的属性(标题或占位符或替代)值。
如果元素有标题,则返回标题,如果没有,检查占位符,然后是alt。
例如:
>> var v='title';
>> $(this).attr(v);
>> $(this).attr('title');(I want this)
旧解决方案:
for(var i=0;i<t.length;i++){
alert($(this).attr(t[i]));
}
真正的解决方案:(感谢 mplungjan)
var o=$(this);
$.each(t,function(k,v){
alert(typeof o.attr(v));//PROBLEM $(this) is not the right object
});
【问题讨论】:
-
因为 Array 中没有 attr 且 v 不是 jQuery 对象 -
alert(typeof v);