[英]Select div by data attribute with JSON
在我的each()
我想:
隱藏所有div,其中data-infos.grpid = $jQuery(this).data('infos').grpid
顯示下一個div,其中data-infos.ordre = $jQuery(this).data('infos').next_ordre
我不知道如何使用data屬性創建一個“ 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>
這是我要隱藏的代碼
$(document).ready(function(){
$("div[testid]:visible").each(function() {
if($(this).attr('testid') === $(this).data('infos').grpid){
$(this).hide();
}
});
});
讓我知道是否有幫助,在這里您可以檢查屬性===數據值,對於其他檢查也可以這樣做。 謝謝
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();
}
}
});
}
想象一下,首先定義一個數據結構,其中包含要滿足的初始信息:
var dataInfos = {
grpid = "12345",
ordre = "2"
},
nextOrdre;
然后,您將迭代找到要隱藏的一個,然后迭代以顯示與next_ordre對應的另一個:
$("div[testid]:visible").each(function() {
var $this = $(this),
infos = $this.data("infos");
if (infos.grpid === dataInfos.grpid) {
$this.hide();
nextOrdre = infos.next_ordre;
}
}
if (nextOrdre) {
$("div[testid]").each(function() {
var $this = $(this),
infos = $this.data("infos");
if (infos.ordre === nextOrdre) {
$this.show();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.