我的页面上有许多 slider 控件。 它们的行为方式完全相同,我想用一个 JavaScript 函数来驱动 slider 行为。
我正在努力传递触发此功能的 slider 的名称,以及需要受该功能影响的 slider 的名称。
这是我的 HTML 代码
<td>
<input name="ScoreNoSurprises" type="range" min="0" max="100" value="5" step="1"
onchange="showValue(this.value,"ScoreNoSurprises")" />
<span id="ScoreNoSurprises">5</span>
</td>
还有我的 JavaScript
<script type="text/javascript">
function showValue(newValue, elementID)
{
window.alert("Element is: " + elementID);
document.getElementById(elementID).innerHTML=newValue;
}
</script>
这可能吗?我究竟做错了什么? 提前致谢。
最佳答案
您正在嵌套引号。
解析器会将 onchange="showValue(this.value,"ScoreNoSurprises")"
读取为 onchange="showValue(this.value,"
,这会引发错误。
然后它会读取 HTML:ScoreNoSurprises")"
,但什么也不做。
此外,您可以使用事件。 (请注意,在本示例中,您必须向输入元素添加类名)
//You can use this instead of onchange=""
Array.prototype.forEach.call(//Changing 'this' for Array.forEach
document.getElementsByClassName("ScoreNoSurprises"),function(element){
//This uses the Array.forEach method in the Element Pseudo array returned by document.getElementsByClassName.
//In other words this will select every element classed as "ScoreNoSurprises"
//which IS better if you have many of these elements, and it keeps JavaScript off the HTML, so there will be less cluttering.
element.addEventListener("change",function(){
//This adds an 'change event listener to Event'
showValue(element.value,"ScoreNoSurprises");
},false);
});
function showValue(newValue, elementID)
{
window.alert("Element is: " + elementID);
document.getElementById(elementID).innerHTML=newValue;
}
<input name="ScoreNoSurprises" class="ScoreNoSurprises" type="range" min="0" max="100" value="5" step="1" /><!--No onchange needed!-->
<span id="ScoreNoSurprises">5</span>
关于javascript - 通过引用将 elementId 传递给 getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35761613/