将数据属性的值附加到dom

时间:2014-06-26 06:47:37

标签: javascript jquery html5

我想用jquery提取date-res和data-ref的值,并将其附加到它的div。

<div id="grid">
<div class="item blue" date-res="8" date-ref="13" data-groups='["all", "letters", "blue", "square"]'>D</div>
<div class="item green" date-res="9" date-ref="10" data-groups='["all", "letters", "blue", "square"]'>E</div>
<div class="item green" date-res="2" date-ref="7" data-groups='["all", "letters", "blue", "square"]'>F</div>
</div>

4 个答案:

答案 0 :(得分:2)

使用.data(),您可以获取uts属性

的值

您需要将html从date-res更改为data-res

 <div id="grid">
    <div class="item blue" data-res="8" data-ref="13" data-groups='["all", "letters", "blue", "square"]'>D</div>
    <div class="item green" data-res="9" data-ref="10" data-groups='["all", "letters", "blue", "square"]'>E</div>
    <div class="item green" data-res="2" data-ref="7" data-groups='["all", "letters", "blue", "square"]'>F</div>
    </div>

和jQuery:

$(document).ready(function(){
    $('.item').each(function(index){
        var res = $(this).data('res');
        var ref = $(this).data('ref');
        $(this).append(res).append(ref);
    });
});

如果你不能改变html,试试这个:

$('.item').each(function(index){
    var res = $(this).attr('date-res');
    var ref = $(this).attr('date-ref');
    $(this).append(res).append(ref);
});

答案 1 :(得分:1)

尝试使用.append(val1,val2)

$('#grid div.item[data-res][data-ref]').each(function(){
  var $this = $(this);
  $this.append($this.data('res'),$this.data('ref'));
})

DEMO

您的html包含错误的属性名称,而不是data-,因此请使用

<div id="grid">
    <div class="item blue" data-res="8" data-ref="13" data-groups='["all", "letters", "blue", "square"]'>D</div>
    <div class="item green" data-res="9" data-ref="10" data-groups='["all", "letters", "blue", "square"]'>E</div>
    <div class="item green" data-res="2" data-ref="7" data-groups='["all", "letters", "blue", "square"]'>F</div>
</div>

答案 2 :(得分:0)

$('.item').each(function(index){
    var res = $(this).attr('date-res');
    var ref = $(this).attr('date-ref');
    $(this).append(res).append(ref);
});

演示:http://jsfiddle.net/U5FvG/1/

答案 3 :(得分:0)

试试这个:我希望这对你有用。

$("#grid").find('.item').each(function(index,element){

    var res=$(this).attr("date-res");
     var ref=$(this).attr("date-ref");
        $(this).html("res value="+res+"  ref value="+ref);


    })