简体   繁体   English

将对象文字扩展为html5数据属性

[英]Expand object literal as html5 data- attributes

It is possible to expands an object literal as html5 data- attributes? 是否可以将对象文字扩展为html5数据属性?

Having the following object: 具有以下目的:

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

I would like to expand it in a anchor tag in order to get something like this: 我想在锚标记中将其扩展,以获得以下内容:

<a href="#" class="show-modal" data-description="some-text" data-pointer="true" data-speaker="true">Show modal</a>

I tried to use the spread syntax in this way <a href="#" class="show-modal" `${...requirements}`>Show modal</a> But nothing get printed 我试图通过这种方式使用传播语法<a href="#" class="show-modal" `${...requirements}`>Show modal</a>但是什么也没打印

I am now depending on this function that builds an anchor and passes the data dynamically. 我现在依赖于此功能,该功能可以构建锚点并动态传递数据。

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

This function do the job, but i would like to know if it's possible to use spread syntax 这个函数可以完成工作,但是我想知道是否可以使用扩展语法

Thanks in advance 提前致谢

How about straightforwardly using an HTMLElement 's dataset property and then assigning a simplified configuration object to it via Object.assign ... like ... 直接使用HTMLElementdataset属性 ,然后通过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; } 

You can define the data-* attribute as a single JSON string, then use JSON.parse() to create a JavaScript object representation of the .dataset property. 您可以将data-*属性定义为单个JSON字符串,然后使用JSON.parse()创建.dataset属性的JavaScript对象表示形式。

Note the single quote surrounding attribute value within template literal that surrounds valid JSON at HTML string. 请注意,模板文字中的单引号周围属性值围绕HTML字符串处的有效JSON

 const requirements = { 'description': 'some text...', 'pointer': true, 'speaker': true } const a = `<a data-requirements='${JSON.stringify(requirements)}'>click</a>`; document.body.insertAdjacentHTML("beforeend", a); let data = JSON.parse(document.querySelector("a").dataset.requirements); console.log(data, data.description, data.pointer, data.speaker); 

The spread syntax won't do what you want. 传播语法无法满足您的要求。 That's really for including key/value pairs from one object into another, or for destructuring assignment. 这实际上是为了将一个对象的键/值对包含到另一个对象中,或者用于破坏分配。

You can use Object.entries() with .map() and .join() inside a template literal. 您可以在模板文字内部将Object.entries().map().join()使用。

 const requirements = { 'data-description': 'some text...', 'data-pointer': true, 'data-speaker': true }; const s = `<a href="#" class="show-modal" ${Object.entries(requirements).map(([k, v]) => k + "='" + v + "'").join(" ")}>Show modal</a>`; console.log(s); 


I think it would be cleaner to move the attribute creation into its own function. 我认为将属性创建移至其自己的功能会更清洁。

 const requirements = { 'data-description': 'some text...', 'data-pointer': true, 'data-speaker': true }; const s = `<a href="#" class="show-modal" ${oToA(requirements)}>Show modal</a>`; console.log(s); function oToA(obj) { return Object.entries(obj) .map(([k, v]) => k + "='" + v + "'") .join(" ") } 

You could enhance the function by replacing embedded quotes with HTML entities. 您可以通过用HTML实体替换嵌入式引号来增强功能。

From MDN: MDN:

Spread syntax allows an iterable such as an array expression to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. 扩展语法允许将可迭代程序(例如数组表达式)扩展到期望零个或多个参数(用于函数调用)或元素(用于数组文字)的位置,或者将对象表达式扩展在零个或多个键-值对(用于对象文字)是期望的。

Since you are trying to build a function that takes in the requirements as arguments (not key/value pairs), an array structure would make better sense than an object structure. 由于您试图构建一个将需求作为参数(而不是键/值对)的函数,因此数组结构比对象结构更有意义。

 const requirements = [ {'data-description': 'some text...'}, {'data-pointer': true}, {'data-speaker': true} ]; (function populate(){ var anchor = document.createElement("a"); // Convert the arguments object to an array and enumerate it // so that each object key can become an attribute and the // corresponding value can become the value: Array.prototype.slice.call(arguments).forEach(function(arg){ for(var prop in arg){ anchor.setAttribute(prop, arg[prop]); } }); console.log(anchor); })(...requirements); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM