简体   繁体   English

如何传递元素的所有数据属性

[英]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.我希望能够传递元素的所有data属性,而不必单独指定它们。 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.但是,当我简单地提供elem.data()时,实际上并没有通过。 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.由于您使用的是 jQuery data()方法,我假设这里的elem是 jQuery object。

You can use native elements dataset property for this, like您可以为此使用本机元素dataset属性,例如

{...elem.get(0).dataset} along with JS spread operator {...elem.get(0).dataset}以及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)

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

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