javascript - 通过引用将 elementId 传递给 getElementById

标签 javascript html

我的页面上有许多 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/

相关文章:

javascript - Canvas 粒子交互图像

javascript - 将数组渲染为组件

javascript - axios POST 上的 PHP Post 数组为空

javascript - 动态标签,单独的标签导航

html - 允许 div 滚动设置在另一个 div 后面

javascript - 编辑元素属性不起作用

javascript - Flot: Markings - 线条描边的大小

javascript - 带有 Spritely 的 jQuery Sprite

javascript - 如何防止 Visual Studio Code 将链式函数推到新行?

html - flex 元素如何在被迫到新行时保持相同的尺寸?