同时知道如何创建基于计数的变量列表(请参见Create dynamic variable names based on count result)。
但是现在我还需要知道如何在到目前为止看起来像这样的过滤器函数内使用此动态变量列表:
$("div.item")
.filter(function( index ) {
return $(this).data("sample1") == samplevariable1 &&
$(this).data("muster1") == mustervariable1;
}).css( "border", "3px double red" );
可以有1到x个动态创建的变量,而不是SampleVariable1,SampleVariable2。
如何重写现有的过滤器函数,以便可以根据需要将其用于尽可能多的变量?
谢谢您的帮助!
JSFiddle: https://jsfiddle.net/SchweizerSchoggi/30od7vf8/58/
答案 0 :(得分:1)
在以下基于your provided fiddle的解决方案中,您将找到:
data-sample1
或data-muster1
)中的let divIndex = i+1;
/* N: used to generate N initial values as arrays */
const SEGMENT_COUNT = 2;
/* contains two dynamically generated arrays */
var generatedData = {elementsCount: 0, sample: [], muster: []};
/* Generate dynamic variables:
Creates two arrays named 'sample' and
muster' inside sampleMusterArrays. These arrays are each filled with elementsCount elements (so that elements can be index from 0 to elementsCount-1 ). */
function generateValues(sampleMusterArrays, elementsCount) {
for (let i = 0; i < elementsCount; i++) {
sampleMusterArrays.sample[i] = i+1;
sampleMusterArrays.muster[i] = i+1;
}
sampleMusterArrays.elementsCount = elementsCount;
}
function modifyGeneratedValues() {
// modify FIRST value in sample-array
generatedData.sample[0] = '2';
// modify SECOND value in sample-array
generatedData.sample[1] = 'x';
// modify FIRST value in muster-array
generatedData.muster[0] = '3';
// modify SECOND value in muster-array
generatedData.muster[1] = 'x';
}
/* filter DIVs with class "item" based on matching sampleMusterArrays to corresponding data-values */
function highlightFilteredDivItems(sampleMusterArrays) {
$( "div.item" )
.filter(function( index ) {
let foundMatch = false;
for (var i=0; i < sampleMusterArrays.elementsCount; i++) {
let divIndex = i+1;
foundMatch = foundMatch ||
$(this).data("sample"+divIndex) == sampleMusterArrays.sample[i] &&
$(this).data("muster"+divIndex) == sampleMusterArrays.muster[i];
} // end for-loop
return foundMatch;
}).css( "border", "3px double red" );
}
/* MAIN */
// generate data
generateValues(generatedData, SEGMENT_COUNT);
console.log("--- generated values: ", generatedData);
/* do other stuff in between */
/* e.g. arbitratily modify generated data */
modifyGeneratedValues();
console.log("--- modified generated values: ", generatedData);
// only the first Div should be marked
highlightFilteredDivItems(generatedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="item" data-sample1="2" data-muster1="3">Div 1</div>
<div class="item" data-sample1="3" data-muster1="3">Div 2</div>
<div class="item" data-sample1="4" data-muster1="3">Div 3</div>