【问题标题】:Collect multiple json objects from data attribute从数据属性中收集多个 json 对象
【发布时间】:2016-11-28 15:14:11
【问题描述】:

我有 3 个按钮元素,在这些元素上我已将相同类型的 JSON 对象分配给数据属性。我以为我可以将这些对象放入一个数组中,但我只能从第一个匹配中得到一个对象。

这是我的 jQuery:

var configs = $("button[id*='alertbtn']").data('config');

我已验证我的选择器

$("button[id*='alertbtn']")

定位正确的三个元素。

是否有可能使用一行代码实现我想要的?

【问题讨论】:

    标签: jquery json


    【解决方案1】:

    ?是的。一个函数调用?没有。:-)

    var configs = $("button[id*='alertbtn']").map(function() { return $(this).data('config'); }).get();
    

    更具可读性:

    var configs = $("button[id*='alertbtn']")
                    .map(function() { return $(this).data('config'); })
                    .get();
    

    使用map 获取配置对象集,然后使用get 获取jQuery 集的内容作为数组。


    这是 ES2015 及更高版本中的一个 可读 行:

    let configs = Array.from($("button[id*='alertbtn']")).map(e = > $(e).data('config'));
    

    【讨论】:

      猜你喜欢
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 2017-08-26
      • 2013-02-28
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      相关资源
      最近更新 更多