首页 > 解决方案 > 将 JS 值传递给 HTML 以创建锚标记

问题描述

我试图将年份值传递给 a 标签,包括“#”,这样我就可以使用滑块年份值作为指向页面下方 div 的链接。

我需要改变什么?

var slider = document.getElementById("myRange");
var output = document.getElementById("year");
output.innerHTML = slider.value; // Display the default slider value

// Update the current slider value (each time you drag the slider handle)
slider.oninput = function() {
  output.innerHTML = this.value;
}

document.getElementById("year").href = year;
<div class="slidecontainer">
  <input type="range" min="2009" max="2020" value="1" class="slider" id="myRange">
</div>

<a href="#" id="year">
</a>

标签: javascripthtmlvariablesslideranchor

解决方案


将值分配给oninput事件处理程序中的 href 属性。

var slider = document.getElementById("myRange");
var output = document.getElementById("year");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
  output.href = '#' + this.value;
}
/* Display the current 'href' value for demo */
a::after {
  content: 'href=' attr(href);
  margin-left: 10px;
  font-size: .8em;
  color: #666;
}
<div class="slidecontainer">
  <input type="range" min="2009" max="2020" value="1" class="slider" id="myRange">
</div>

<a href="#" id="year">
</a>


推荐阅读