2016-03-03 92 views
0

我在页面上有许多滑块控件。 它们的行为完全一样,我想用一个JavaScript函数来驱动滑块行为。通过引用传递elementId到getElementById

我很努力地通过触发此功能的滑块的名称,哪个是需要受该功能影响的名称。

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

这可能吗?我究竟做错了什么? 在此先感谢。

+0

onchange =“showValue(this.value,”ScoreNoSurprises“)” - “inside of”!改变内在的“s!” –

+0

当然!这很尴尬,非常感谢。 – Maxcot

回答

1

您正在嵌套报价。 解析器会将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>
确实看看第一手更加复杂,但随着代码变得更复杂,可能是有益的消除重复,并控制一个点的所有代码。 在某些情况下这可能会更好。