1

こんにちは私はjquery関数を使用してすべてのタグ属性を取得しています。今はそれらを1つに格納して本文に追加したいのですが、それを実行する方法を見つけることができません。これがフィドルリンクです

<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>
4

3 に答える 3

1

raw 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>');

ここでのフィドルの例

于 2012-08-27T13:18:47.480 に答える
1

以下のこの関数を使用して、すべての属性を読み取り、それらを配列にプッシュできます。

デモ: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>')   
    });
});
于 2012-08-27T13:18:55.203 に答える
1

配列を使用して検索する属性を格納し、その配列を繰り返し処理して$.eachすべての値を検索し、それらを文字列に集中させて、すべてを一度に追加すると、より効率的になります。

$(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);
    });
});​

フィドル

于 2012-08-27T13:23:51.040 に答える