sách gpt4 ăn đã đi

javascript - 将对象字面量扩展为 html5 数据属性

In lại Tác giả: Walker 123 更新时间:2023-11-29 16:40:28 26 4
mua khóa gpt4 giày nike

可以将对象文字扩展为 html5 数据属性吗?

具有以下对象:

const requirements = {
'data-description': 'some text...',
'data-pointer': true,
'data-speaker': true
}

我想将其扩展为 anchor 标记以获得如下内容:

Show modal

我尝试以这种方式使用扩展语法 Show modal但没有打印任何内容

我现在依赖这个函数来构建 anchor 并动态传递数据。

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;
}

这个函数可以完成这项工作,但我想知道是否可以使用扩展语法

Cảm ơn trước

câu trả lời hay nhất

直接使用 HTMLElement's dataset property 怎么样?然后通过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; }

关于javascript - 将对象字面量扩展为 html5 数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46632795/

26 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress