javascript - 使用 JSON 按数据属性选择 div

标签 javascript jquery json

在我的 each() 中,我想:

  1. 隐藏所有 data-infos.grpid = $jQuery(this).data('infos').grpid

  2. 显示下一个 div,其中 data-infos.ordre = $jQuery(this).data('infos').next_ordre

我不知道如何使用数据属性创建“where”并对其进行“隐藏”或“显示”。

jQuery("div[testid]:visible").each(function() { 
    //Hide all div with same data-infos grpid
    //display the next one with 'next_ordre' (ordre=2 in this example)
});     
<div testid="afcnG0tN" data-infos='{"banid":"3cxWET0T", "grpid":"12c0RNPo", "ordre":"1", "next_ordre":"2"}'>Test 1</div>
<div testid="afcnG0tN" data-infos='{"banid":"0i9fIbei", "grpid":"12c0RNPo", "ordre":"2", "next_ordre":"3"}' style="display: none">Test 2</div>
<div testid="afcnG0tN" data-infos='{"banid":"pTgfUFLf", "grpid":"12c0RNPo", "ordre":"3", "next_ordre":"1"}' style="display: none">Test 3</div>

最佳答案

jQuery("div[testid]:visible").each(function() { 
    var $that = $(this),
        data = $that.data('infos'),
        hideDivs = getTargetDiv('grpid', data.grpid),
        showDivs = getTargetDiv('ordre', data.next_ordre);

    hideDivs.forEach(function($div) {
        $div.hide();
    });

    showDivs.forEach(function($div) {
        $div.show();
    });
});

// Select some divs that pass the given check
function getTargetDiv (key, value) {
    var results = [];
    $('[data-infos]').each(function () {
        var $that = $(this),
            data = $that.data('infos');

        if(data[key] == value) results.push($that);
    });

    return results;
}

工作中的 JSFiddle: https://jsfiddle.net/LeoAref/fxzhfvoz/

<小时/>

另一种方式:

jQuery("div[testid]:visible").each(function() { 
    var $that = $(this),
        data = $that.data('infos');

    doActionOnTargetDiv('grpid', data.grpid, 'hide');
    doActionOnTargetDiv('ordre', data.next_ordre, 'show')
});

function doActionOnTargetDiv (key, value, action) {
    $('[data-infos]').each(function () {
        var $that = $(this),
            data = $that.data('infos');

        if(data[key] == value) {
            if(action === 'hide') {
                $that.hide()
            } else if(action === 'show') {
                $that.show();
            }
        }
    });
}

关于javascript - 使用 JSON 按数据属性选择 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36448133/

相关文章:

javascript - Passport + NodeJs + Express 得到 "req.user"undefined

javascript - $(selector).val() 不起作用

java - 如何使用 Jolt 按两个键聚合 JSON 数据?

jQuery - IE8 中的动画不透明度

java - 从 java/android 获取 web api/asp token

json - 将单元格 a1 中的 JSON 数据提取到 b1、c1、d1 等中。 - Excel

javascript - 我可以在我的 CSS 样式表中链接外部 javascript 吗?

javascript - 从外部访问闭包内定义的 var(即定义闭包的范围)

javascript - 无法将html表数据绑定(bind)到mvc Controller 模型

javascript - 自定义 Clockdown.js 以仅显示分钟和秒