js
function test()
{
var thisone = $('#idforelement').data('thisone');
var secondone = $('#idforelement2').data('secondone');
}
html
<div id="idforelement" data-thisone="Hello world!"></div>
Is correct use data from html side to inside a function like on idforelement at html?
Or another ways to do it?
Thanks
What’s the idea of: function test(thisone,secondone) ?
Why do you pass these arguments?
Ah is not needed. Just try to got the idea when is useful pass the data value from html side to a javascript function as a value?
Thanks.
Ok. Yes, it’s correct to use it inside a function. This is not restricted to the data()-function. You can access html-nodes anywhere and read or modify them, eg:
$(’#idforelement’).css(“color”, “yellow”);
A usecase for data() may be:
<button id="mybutton" data-ids="id1,id2">Click</button>
<div id="id1">1</div>
<div id="id2">2</div>
$('#mybutton').click(function(){
var a =$(this).data('ids').split(',');
for(var i=0; i<a.length; i++) {
$('#'+a[i]).css("color", "red");
}
});
When clicking the button then 2 divs will be modified.
And the button stores the information, which divs should be modified, in the data-ids-attribute.
1 Like