2015-08-08 62 views
0
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)值。jQuery的GET ATTR值

如果元素有標題,則返回標題,如果沒有,則選中佔位符,然後alt。

例如:

>> var v='title'; 
>> $(this).attr(v); 
>> $(this).attr('title');(I want this) 

舊SOLUTION:

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 
}); 
+1

因爲在數組沒有ATTR和v不是一個jQuery對象 - '警告(ty​​peof運算V);' – mplungjan

回答

2

這裏是什麼,我相信你正在嘗試做的。

單擊該字段,並期待在控制檯

$(function() { 
 
    var t=['title','placeholder','alt']; 
 
    $("input").on("focus",function() { // we need an event 
 
    var inp = $(this); // the input as a jQuery object 
 
    $.each(t,function(_,key) { // in here, $(this) is NOT the input 
 
     console.log(key+":"+inp.prop(key)); // we use prop instead of attr 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input id="inp1" type="text" title="Some input field" placeholder="Enter some text" />

1

試試這個..

$ .each()函數與$(selector).each()不同,它用於遍歷一個jQuery對象。 $ .each()函數可用於遍歷任何集合,無論它是對象還是數組。在數組的情況下,每次回調都會傳遞一個數組索引和相應的數組值。 (該值也可以通過this關鍵字訪問,但是Javascript始終將此值作爲Object包裝,即使它是簡單的字符串或數字值。)該方法返回其第一個參數,即迭代的對象。

$.each([ 52, 97 ], function(index, value) { 
    alert(index + ": " + value); 
}); 

http://api.jquery.com/jquery.each/

您的代碼

var t=new Array('title','placeholder','alt'); 

    $.each(t,function(k,v){ 
     alert("key:"+k+"value:"+v); 
    }); 

演示:http://jsfiddle.net/so2pp1tp/

+0

我有更新演示鏈接檢查它,讓我知道 –

+0

對不起,我的目標是獲取屬性值,使用數組中的名稱,問題是attr函數不工作。不能得到價值,但只有「未定義」 – xtr3mz

+0

你想要的HTML動態attr像「標題」? –