是否可以将对象文字扩展为 html5 数据属性?
具有以下对象:
const requirements = {
'data-description': 'some text...',
'data-pointer': true,
'data-speaker': true
}
我想将其扩展为锚标记以获得如下内容:
<a href="#" class="show-modal" data-description="some-text" data-pointer="true" data-speaker="true">Show modal</a>
我尝试以这种方式使用扩展语法<a href="#" class="show-modal" `${...requirements}`>Show modal</a>
但什么也没有打印出来
我现在依赖这个函数来构建锚点并动态传递数据。
function buildAnchor(requirements) {
const anchor = document.createElement('a');
anchor.setAttribute('class', 'show-modal');
anchor.setAttribute('href', '#');
anchor.textContent = 'More info';
Object.keys(requirements).forEach(data => {
anchor.setAttribute(data, requirements[data]);
});
return anchor.outerHTML;
}
这个函数可以完成这项工作,但我想知道是否可以使用扩展语法
提前致谢
直接使用如何HTMLElement's dataset财产 https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset然后通过分配一个简化的配置对象给它Object.assign
... 喜欢 ...
var requirements = {
'description': 'some text...',
'pointer': true,
'speaker': true
};
var elmLink = document.createElement('a');
elmLink.href = '';
Object.assign(elmLink.dataset, requirements);
console.log('elmLink : ', elmLink);
.as-console-wrapper { max-height: 100%!important; top: 0; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)