将JS值传递给HTML以创建锚标记

问题描述 投票:0回答:2

[我正在尝试将年份值传递到包含“#”的标签,以便随后可以将滑块年份值用作到页面下方的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>
javascript html variables slider anchor
2个回答
2
投票

将值分配给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>

0
投票

您正在将href设置为year,但尚未定义(正如您在问题中所看到的)。您只需在output功能中设置oninput href。因此,您的代码将如下所示:

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;
  output.href = '#' + this.value;
}
© www.soinside.com 2019 - 2024. All rights reserved.