在我的 each()
中,我想:
隐藏所有
data-infos.grpid = $jQuery(this).data('infos').grpid
显示下一个 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/