設置 dataset 會將所有變數的數值變成(string)類別
var x = {
a: 1,
b: '0',
c: '',
d: undefined,
e: null
};
/* ------------------------ */
var div_1 = document.querySelector('#div_1');
// set dataset
for (var key in x) {
var element = x[key];
div_1.dataset[key] = element;
}
/* ------------------------ */
<div id="div_1" data-a="1" data-b="0" data-c="" data-d="undefined" data-e="null">
div_1
</div>
/* ------------------------ */
console.dir(div_1.dataset);
/* ------------------------ */
for (var key in div_1.dataset) {
var element = div_1.dataset[key];
console.log(key, ' => ', element, ', type=', typeof element);
}
--------------------------------------------------------------------------
a => 1 , type= string
b => 0 , type= string
c => , type= string
d => undefined , type= string
e => null , type= string
--------------------------------------------------------------------------
// 解決辦法
div_1.dataset.data = JSON.stringfy(x);