Reputation: 102
I have a div which looks like this:
<div class="enemy" data-level="1" data-dmg="10" data-hp="50" data-type="A" data-ready_to_breed="false"><span>Enemy 1</span></div>
How can display what is in the data tags in the <span>
in such a way that the user always has a view into the the state of the div (or "enemy")
Upvotes: 2
Views: 128
Reputation: 87073
To access the data
property use .data()
.
$('.enemy').data('type'):
$('.enemy').data('ready_to_bread'):
and so on.
To display to the span
about enemy
try:
var enemy = $('.enemy');
$('span', enemy).html(enemy.data('type'))
var enemy = $('.enemy'),
var data = enemy.data();
$.each(data, function(key, val) {
enemy.append($('<span/>', {
'class' : key, // if you need then can add class like this
html: key + " : " + val + '<br>'
}));
});
Upvotes: 5
Reputation: 136114
You could append new elements inside the div like this:
$('.enemy').each(function(){
var $this = $(this);
$this.children().append($('<span />').html('Level: ' + $this.data('level')));
$this.children().append($('<span />').html('Dmg: ' + $this.data('dmg')));
});
Live example: http://jsfiddle.net/ZJDEu/
This will result in markup such as:
<div class="enemy" data-ready_to_breed="false" data-type="A" data-hp="50" data-dmg="10" data-level="1">
<span>
Enemy 1
<span>Level: 1</span>
<span>Dmg: 10</span>
</span>
</div>
Of course you could change the jquery to form any markup you wish.
If it were me I would go for something slightly different:
$('.enemy').each(function(){
var $this = $(this);
$this.append($('<span />').addClass('level').html($this.data('level')));
$this.append($('<span />').addClass('dmg').html($this.data('dmg')));
});
which forms the markup:
<div class="enemy" data-ready_to_breed="false" data-type="A" data-hp="50" data-dmg="10" data-level="1">
<span>Enemy 1</span>
<span class="level">1</span>
<span class="dmg">10</span>
</div>
As this is slightly easier to deal with for styling/layout purpose.
Live example: http://jsfiddle.net/djdAB/
Upvotes: 1