javascript - 每个单独 ID 的 jQuery min(最小值)

标签 javascript jquery algorithm each min

我在一个页面上有超过 2 个带价格的旅行,每个旅行(div 容器)都应该有一个起始价格(最小值)。

所以我写了这个,它正在工作......

jQuery(function($) {
    var vals = $('.prices').map(function () {
    return parseInt($(this).text(), 10) ? parseInt($(this).text(), 10) :  null;
    }).get();

// then find their minimum
    var min = Math.min.apply(Math, vals);

// tag any cell matching the min value
    $('.prices').filter(function () {
    return parseInt($(this).text(), 10) === min;
    });

   $('.start-price').text(min);
});

但显然该脚本从页面(所有容器)上的所有价格中获取最小值。它应该从每次(每次)旅行中取最小值。容器的 ID 可以动态生成。 我怎样才能做到这一点?

最佳答案

确保每个旅行 div 都有一个类(比方说 .travel)并为每个进行计算。

jQuery(function($) {      
    $(".travel").each(function() {

      var $prices = $(this).find(".prices");
      var vals = $prices.map(function () {
        return parseInt($(this).text(), 10) ? parseInt($(this).text(), 10) :  null;
      }).get();

      // then find their minimum
      var min = Math.min.apply(Math, vals);

      // tag any cell matching the min value
      $prices.filter(function () {
        return parseInt($(this).text(), 10) === min;
      });
      $(this).find('.start-price').text(min);
    });       
});

关于javascript - 每个单独 ID 的 jQuery min(最小值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48429065/

相关文章:

javascript - 添加指向数组中图像的链接

javascript - 无法在数据表中加载 json 文件

javascript - 必须触发两次点击事件才能在 ipad 上触发全屏模式

javascript - 如何确保按钮事件在 Javascript/JQuery 中只触发一次?

javascript - AngularJS - 在 Controller 之间共享范围值

javascript - 如何使用 filepond 插件、ajax 和 php,在服务器上未检测到文件名

javascript 函数返回未定义但 console.log() 打印预期值

arrays - 算法:根据约束对数组中的对象进行排序

algorithm - 在 DAG 中合并不可达的顶点可能会产生循环?

algorithm - NFA 到 DFA 转换的简洁描述?