通过引用将elementId传递给getElementById

时间:2016-03-03 01:46:50

标签: javascript html

我在页面上有许多滑块控件。 它们都以完全相同的方式运行,我想用一个JavaScript函数来驱动滑块行为。

我正在努力传递触发此功能的滑块的名称,以及需要受该功能影响的滑块的名称。

这是我的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>

这可能吗?我究竟做错了什么? 提前致谢。

1 个答案:

答案 0 :(得分:1)

您正在嵌套引号。 解析器会将onchange="showValue(this.value,"ScoreNoSurprises")"读为onchange="showValue(this.value,",这会引发错误。

然后它会读取HTML:ScoreNoSurprises")"什么都不做。

此外,您可以使用事件。 (注意,在此示例中,您必须向输入元素添加类名)

&#13;
&#13;
//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;
   }
&#13;
<input name="ScoreNoSurprises" class="ScoreNoSurprises" type="range" min="0" max="100" value="5" step="1" /><!--No onchange needed!-->
    <span id="ScoreNoSurprises">5</span>
&#13;
&#13;
&#13; 这个确实看起来更复杂,但随着代码变得越来越复杂,它可能有助于消除重复,并在一个点上控制所有代码。 在某些情况下这可能会更好。

相关问题