代码之家  ›  专栏  ›  技术社区  ›  Kyle Underhill

获取两个值之间的百分比差异(多个实例)

  •  1
  • Kyle Underhill  · 技术社区  · 6 年前

    我正试图得到 result 要在的每个实例上运行的函数 item . 这个 结果 应该是 percentage 属于 value / max . 当我使用时,函数不运行 value max 作为变量。

    $(".list").each(function() {
      var value = $(this)
        .closest(".item")
        .find(".value")
        .val();
      var max = $(this)
        .closest(".item")
        .find(".max")
        .val();
      var result = parseInt($(value) * 100) / parseInt($(max));
    
      if (!isFinite(result)) result = 0;
    
      $(".percent").val(result);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="list">
      <div class="item">
        <div>Value
          <label>
        <input class="value" value="10" type="text">
      </label>
        </div>
        <div>Max
          <label>
        <input class="max" value="50" type="text">
      </label>
        </div>
        <div>% Complete
          <label>
        <input class="percent" type="text">
      </label>
        </div>
      </div>
      <div class="item">
        <div>Value
          <label>
        <input class="value" value="40" type="text">
      </label>
        </div>
        <div>Max
          <label>
        <input class="max" value="50" type="text">
      </label>
        </div>
        <div>% Complete
          <label>
        <input class="percent" type="text">
      </label>
        </div>
      </div>
    </div>
    3 回复  |  直到 6 年前
        1
  •  1
  •   sftt    6 年前

    谢谢@mridula的回答 请考虑一下

    $(".list .item").each(function() {
        const item = $(this);
    
        const value = item
            .find(".value")
            .val();
    
        const max = item
            .find(".max")
            .val();
    
        let result = parseInt(value * 100) / parseInt(max);
    
        if (!isFinite(result)) result = 0;
    
        item.find('.percent').val(result);
    });
    
        2
  •  3
  •   mridula    6 年前

    value max 只不过是保存要用来计算的字符串值的变量。

    替换

     var result = parseInt($(value) * 100) / parseInt($(max));
    

    通过

    var result = parseInt(value) * 100 / parseInt(max);
    
        3
  •  1
  •   Manish    6 年前

    你得不到百分比 差异 在上述答案的两个值之间,因为与其他值相比,您只得到第一个值的百分比

    试试这个

    $(".item").each(function(element) {         
    
      var v1 = $(this).find("input.value").val(); 
    
      var v2 =  $(this).find("input.max").val();
    
      var maxV =Math.max(parseInt(v1),parseInt(v2));
    
      var minV =Math.min(parseInt(v1),parseInt(v2));
    
      var difV =maxV- minV;
    
        var result = (difV * 100) / maxV;   
    
        $(this).find("input.percent").val(result);      
    

    (});