Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

javascript - Use dynamically created variables in jQuery filter function

Meanwhile know how to create a Count based list of Variables (see Create dynamic variable names based on count result).

But now I also need to know how to use this dynamic list of variables inside a filter function that looks like this so far:

$("div.item")
  .filter(function( index ) {
  return $(this).data("sample1") == samplevariable1 &&
         $(this).data("muster1") == mustervariable1;
}).css( "border", "3px double red" );

There can be 1 to x dynamically created Variables instead of SampleVariable1, SampleVariable2.

How can I rewrite my existing filter function so that I can use it for as many variables as needed?

Thank you for your help!!

JSFiddle: https://jsfiddle.net/SchweizerSchoggi/30od7vf8/58/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Supposed you want to highlight a DIV-list based on matching some generated values

In the following solution based on your provided fiddle you will find:

  • a generator-function which fills two arrays with consecutive numbers (generates up to N values). See answered array-approach to your corresponding question Create dynamic variable names based on count result
  • a modification-function which simulates some changes of the previously generated values (as this could happen in your script as you said)
  • a filter-and-highlight-function which selects HTML-elements using jQuery (for DIV elements with class 'item') and filter them based on matching their DATA-attributes with the corresponding array-elements. This filtered HTML-elements will be highlighted using specified CSS-border.

Note: different indexing

  • An array in JS usually is indexed starting with 0 (first element) and ending with N (where array has N+1 elements).
  • Your data-attributes inside the HTML's DIV-elements (i.e. data-sample1 or data-muster1) are indexed starting with 1. So the solution has defined a special index-variable: 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...