首页 > 解决方案 > 我如何获得每个滑块的价值;javascript只显示一个

问题描述

我很难做到这一点,如果有人知道一个非常感谢的解决方案,我希望得到一些帮助。!仍在学习 java-script 并最终学习加载功能,但现在我在尝试显示两个值时遇到了问题。如果我改变任何东西,我会让第二个滑块工作,但第一个滑块停止工作。

HTML 代码:

    <input type="range" min="1" max="100" value="1" class="slider" id="myRange">
    <p id="value-box">Value: <span id="demo" style="color:#ae81ff;"></span><name id="Seconds"> Seconds</id></p>
    <input type="range" min="1" max="200" value="1" class="slider" id="W-range">
    <p id="value-box">Value: <span  Name="W-range" id="demo2" style="color:#ae81ff;"></span><name id="Seconds"> Seconds</id></p>

Javascript代码:

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");

output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
  }

window.onload = ()=>{
    var slider = document.getElementById("W-range");
    var output = document.getElementById("demo2");
    output.innerHTML = slider.value;
    
    slider.oninput = function() {
      output.innerHTML = this.value;
    }
      }

标签: javascripthtmlslider

解决方案


首先将slider变量设置为myRange滑块,然后重新定义slider并将其指向W-range滑块。您应该有两个单独的变量。window.onload此外,如果您只是将您的放在结束标签script之前,则根本不需要。body

此外,没有nameHTML 元素,然后您获得了带有结束id标签的元素,该标签也不存在。这些应该只是span元素。而且,你不能有两个相同的元素id,你正在用id="Seconds". 实际上,您应该首先避免使用id's,因为它们会使您的代码更脆弱且更难扩展。这些元素在这里根本不需要唯一的名称。

此外,由于两个滑块的作用相同,因此您只需编写一次回调代码。请参阅下面的内联评论:

<input type="range" min="1" max="100" value="1" class="slider" id="myRange">
<p id="value-box">Value: 
   <span style="color:#ae81ff;"></span>
   <span> Seconds</span>
</p>

<input type="range" min="1" max="200" value="1" class="slider" id="W-range">
<p id="value-box">Value: 
  <span style="color:#ae81ff;"></span>
  <span> Seconds</span>
</p>

<script>
  // If you place a `script` element just before the closing body tag
  // there is no need for window.onload because by the time the parser
  // reaches this point, all the HTML will have been loaded into memory
  
  // Don't use event properties, use addEventListener()
  document.getElementById("myRange").addEventListener("input", report);
  document.getElementById("W-range").addEventListener("input", report);  
  
  // Both sliders essentially need to do the same thing, but their values
  // need to go in different places. `this` will represent the slider
  // that got the input and then we can get the paragraph sibling that
  // comes after it and query its contents for the span that should display
  // the value.
  function report(event){
   this.nextElementSibling.querySelector("span").textContent = this.value;  
  }

</script>


推荐阅读