2012-08-27 53 views
1

您好我正在使用jquery函数获取所有标签属性,现在我想将它们存储到一个并追加到正文中,但无法找到如何完成它的方式。这里是fiddle链接在jquery中添加两个以上的变量到一个变量

<head> 
<script type="text/javascript"> 
$(function(){ 
$('a').click(function(){ 
var name= $(this).attr('name'); 
var href= $(this).attr('href'); 
var jj= $(this).attr('class'); 
var user_id= $(this).attr('user_id'); 
var page_type= $(this).attr('page_type'); 
var price= $(this).attr('price'); 
var bonus= $(this).attr('bonus'); 
var wrapper= $(this).attr('wrapper'); 
var token= $(this).attr('token'); 
var own= $(this).attr('own'); 
$('body').append('<div>'+name+'<div>') 
})}) 
</script> 
</head> 
<body> 
<a id="profile_2902" name="b_now" href="#" class="big_now" user_id="152402569967" page_type="profile" price="292" bonus="0" wrapper="5972569967" token="e644ce48aa43dc3caa348745a" own="4100447132"> 
Click now! 
</a> 
</body> 
+0

您可以向我们展示一下您希望输出的样本吗? – Lix

回答

1

你可以使用原始的js获得所有属性和使用jQuery像这样打印出来:

var el = document.getElementById("someId"); 
var arr = []; 
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){ 
    arr.push(attrs.item(i).nodeValue); 
} 
$('body').append('<div>'+arr.join(", ")+'<div>'); 

Working fiddle example here

+0

你的功能是什么项目,它有什么用处 – Carlos

+0

它从attrs数组中获取一个项目 – Asciiom

+0

项目是javascript的方法吗?以及为什么我们不能使用attrs [i] – Carlos

1

您可以使用下面这个函数读取所有属性并将它们推入阵列中。

DEMO:http://jsfiddle.net/cuyfK/1/

var el = this, arr = [], it; 
    for (var i = 0, attrs = el.attributes, l = attrs.length; i < l; i++) { 

     it = attrs.item(i); 

     if (it.nodeName == 'id') { 
      arr.push(it.nodeName + '="' + it.nodeValue + '_fixed"'); 
     } else { 
      arr.push(it.nodeName + '="' + it.nodeValue + '"'); 
     } 
    } 

或可能是你想要把一个数组中的特定ATTR值..尝试下面,

$(function() { 
    $('a').click(function() { 
     var attr = []; 
     attr.push($(this).attr('name')); 
     attr.push($(this).attr('href')); 
     attr.push($(this).attr('class')); 
     attr.push($(this).attr('user_id')); 
     attr.push($(this).attr('page_type')); 
     attr.push($(this).attr('price')); 
     attr.push($(this).attr('bonus')); 
     attr.push($(this).attr('wrapper')); 
     attr.push($(this).attr('token')); 
     attr.push($(this).attr('own')); 

     $('body').append('<div>' + attr.join(' ') + '<div>') 
    }); 
}); 
+0

为什么你在你的功能 – Carlos

+0

+1为你的努力使用项目 – Carlos

1

使用一个数组来存储你想要查找的属性,然后就遍历与$.each该数组找到所有的值,并将其concentenate成一个字符串,并附加它们都一气呵成更有效率:

$(function(){ 
    var attributes = ['name', 'href', 'class', 'user_id', 'page_type', 
         'price', 'bonus', 'wrapper', 'token', 'own'] 

    $('a').on('click', function(){ 
     var html='', self=this; 
     $.each(attributes, function(i,e) { 
      html += '<br><div>'+e+' : '+$(self).attr(e); 
     }); 
     $('body').append(html); 
    }); 
});​ 

FIDDLE