【问题标题】:Use dynamically created variables in jQuery filter function在 jQuery 过滤器函数中使用动态创建的变量
【发布时间】:2019-07-11 22:13:36
【问题描述】:

同时知道如何创建基于计数的变量列表(请参阅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/

【问题讨论】:

  • 你能提供工作小提琴吗?它更有助于解决您的问题
  • 构造“动态变量名”的概念出现了很多,几乎 100% 的时间是对 JavaScript 习惯用法的误解和/或未能认识到简单数组的适用性。为什么不能只拥有一个“simpleVariable”数组并使用数字索引?
  • @prasanth 我现在添加了一个小提琴
  • @Pointy 我现在添加了一个小提琴。如何让这变得更容易......?

标签: javascript jquery filter filtering


【解决方案1】:

假设你想根据匹配一些生成的值来突出显示一个 DIV 列表

在以下基于your provided fiddle的解决方案中你会发现:

  • 一个 generator 函数,它用连续数字填充两个数组(最多生成 N 个值)。查看对您相应问题的回答 array-approach Create dynamic variable names based on count result
  • 一个修改-函数,它模拟以前生成的值的一些变化(正如你所说,这可能发生在你的脚本中)
  • 一个 filter-and-highlight-函数,它使用 jQuery 选择 HTML 元素(对于具有类 'item' 的 DIV 元素)并根据匹配它们的 DATA 过滤它们- 具有相应数组元素的属性。过滤后的 HTML 元素将使用指定的 CSS 边框突出显示。

注意:不同的索引

  • JS 中的 数组 通常以 0(第一个元素)开始并以 N(其中数组有 N+1 个元素)结束。
  • HTML 的 DIV 元素(即 data-sample1data-muster1)中的 data-attributes 是从 1 开始索引的。因此解决方案定义了一个特殊的索引变量: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>

【讨论】:

  • 这太棒了!你不仅解决了我的问题,还一步步描述了如何去做,让我可以从中学习。真是太棒了,如果您在同一个办公室,我会请您喝咖啡或其他什么。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 2010-09-12
  • 1970-01-01
  • 2018-02-28
  • 2019-11-08
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多