简体   繁体   中英

How to pass all of an element's data attributes

I want to be able to pass all of an element's data attributes, without have to individually specify them. For example:

function foo(elem) {
  $.ajax({
    type: 'POST',
    data: JSON.stringify(elem.data()),
    ...

However, when I simply supply elem.data() , nothing is actually getting passed. Is there a way to accomplish this without having to individually specify, like:

data: JSON.stringify({ foo: elem.data('foo'), ... })

Since you're using jQuery data() method I'm assuming elem here is a jQuery object.

You can use native elements dataset property for this, like

{...elem.get(0).dataset} along with JS spread operator

 const el = document.querySelector('div'); console.log({...el.dataset});
 <div data-test-id="test" data-test-key="test-key"></div>

Try using the spread operator syntax:

 const foo = { a: 'a', b: 'b', c: 'c' } const boo = { d: 'd', e: 'e', f: 'f' } const foo_boo = {...foo, ...boo } console.log(foo_boo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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