检查多个 div 的数据属性和 return 仅检查存在于单独列表中的那些

Check multiple div's data- attributes and return only those that exist to a separate list

这是我的问题:

HTML 结构如下:

<div class="a-pin" data-alpha=2>City One</div>
<div class="a-pin" data-alpha=3 data-beta=1>City Two</div>
<div class="a-pin" data-beta=2 data-gamma=8>City Three</div>

可以有任意数量的相似 divs 具有不同但相似的 data 属性。不知何故,在 jQuery 的帮助下,我需要检查所选 divdata- 属性和 return(!) 每个 data- 属性及其值的列表在应该如下所示的弹出窗口中(示例中的第二个 div):

项目总数:
阿尔法的东西:3
测试版内容:1

不用担心弹出窗口,它已经在代码中了,应该是这样的:

popupText.html( 'Total projects: <br>' + the-list-that-I-need );

如何实现?

您可以通过使用 data() 检索元素上的所有 data 属性来实现此目的。然后您可以遍历这些以生成所需的 HTML。试试这个:

$('.a-pin').click(function() {
    var data = $(this).data();
    var output = '';
    for (var key in data)
        output += key + ': ' + data[key] + '<br />';
    $('#output span').html(output);
});

Example fiddle

原版,也许有用。

var nodes = Array.prototype.slice.call(document.querySelectorAll('.a-pin')),
    gatherAttributes = function ( node ) {
        return Array.prototype.slice.call(node.attributes).reduce(function ( acc, att ) {
            var name = att.name;
            if (/data.+/.test(name)) acc[name] = node.getAttribute(name);
            return acc;
        }, {});
    };
nodes.forEach(function ( node ) {
    var result = gatherAttributes(node);
    console.log(JSON.stringify(result));
});