多个范围滑块的单一功能

single function for multiple range sliders

我有一个包含多个范围滑块的页面。我想根据值控制输出。是否可以使此功能适用于同一页面上的多个滑块?还是我必须用每个输入的新 ID 重新编写函数?

代码:

$(".slider").mousemove(function () {
  if ($(this).val()==this.min) {
    $(".priceOutputId").text("Less than ")
  }
  else if ($(this).val()==this.max) {
    $(".priceOutputId").text("More than 0")
  }
  else {
    $(".priceOutputId").text("around $" + $(this).val())
  }
}

)
<label class="radio_title">
  <input type="range" min="80" max="100" value="80" class="slider" id="priceInputId">
  <div class="range_output">
    <output name="priceOutputName" class="priceOutputId">Less Than </output>
  </div>
</label>

<label class="radio_title">
  <input type="range" min="80" max="100" value="80" class="slider" id="priceInputId">
  <div class="range_output">
    <output name="priceOutputName" class="priceOutputId">Less Than </output>
  </div>
</label>

要使输出仅与引发事件的元素相关,您需要将逻辑挂接到 this 引用。从那里您可以使用 jQuery 的 DOM 遍历方法,例如 closest()find() 来检索相关元素并更新它们。

另请注意,您不能多次使用相同的 id 属性。它们必须是独一无二的。如果您想按行为对元素进行分组,请使用 class。此外,input 事件更适用于范围滑块控件,因为它在通过键盘更改控件值时也有效。

综上所述,试试这个:

$(".slider").on('input', function() {
  let $label = $(this).closest('label');  
  let $output = $label.find('.priceOutput');

  if (this.value == this.min) {
    $output.text("Less than ")
  } else if (this.value == this.max) {
    $output.text("More than 0")
  } else {
    $output.text("around $" + this.value)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="radio_title">
  <input type="range" min="80" max="100" value="80" class="slider priceInput">
  <div class="range_output">
    <output name="priceOutputName" class="priceOutput">Less Than </output>
  </div>
</label>

<label class="radio_title">
  <input type="range" min="80" max="100" value="80" class="slider priceInputId">
  <div class="range_output">
    <output name="priceOutputName" class="priceOutput">Less Than </output>
  </div>
</label>

另请注意,if 条件可以使用以下三元组缩短。您是否更喜欢简洁而不是易于阅读,由您自己选择:

let output = this.value === this.min ? 'Less than ' : this.value === this.max ? 'More than 0' : 'Around $' + this.value;
$output.text(output);