这是一种基于我的blank.html
模板的方法。
注意:在 setAllFunc3 中,您可以将多个处理程序附加到一个元素。您也可以有选择地删除它们。请参阅另一位成员关于 getAllByClassName 的说明。
另请注意:通过附加处理程序,我们可以访问this
var。这意味着我们知道哪个元素触发了调用。我只是从按钮中提取了文本。您可以改为获取属性的值,然后在处理程序中使用该值。可能你稍后会发现一些东西。:)
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
index=element.className.indexOf(newStr);
if ( index == -1)
element.className += ' '+newStr;
else
{
if (index != 0)
newStr = ' '+newStr;
element.className = element.className.replace(newStr, '');
}
}
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
window.addEventListener('load', mInit, false);
function mInit()
{
}
function getval(inputVar)
{
alert(inputVar + " was passed to getval");
}
function getvalNew(inputVar)
{
alert("getvalNew(" + inputVar + ")");
}
function setAllFunc1()
{
var tgtButtons = document.getElementsByClassName('num');
var i, n = tgtButtons.length;
for (i=0; i<n; i++)
tgtButtons[i].setAttribute('onclick', 'getval(' + i + ')' );
}
function setAllFunc2()
{
var tgtButtons = document.getElementsByClassName('num');
var i, n = tgtButtons.length;
for (i=0; i<n; i++)
tgtButtons[i].setAttribute('onclick', 'getvalNew(' + i + ')' );
}
function myFunc3()
{
var clickedBtn = this;
var btnText = clickedBtn.innerHTML;
alert("You clicked the button labelled: " + btnText);
}
function setAllFunc3()
{
var tgtButtons = document.getElementsByClassName('num');
var i, n = tgtButtons.length;
for (i=0; i<n; i++)
{
tgtButtons[i].removeAttribute('onclick');
tgtButtons[i].addEventListener('click', myFunc3);
}
}
</script>
<style>
</style>
</head>
<body>
<button class="num" onclick="getval(0)">0</button>
<button class="num" onclick="getval(1)">1</button>
<button class="num" onclick="getval(2)">2</button>
<button class="num" onclick="getval(3)">3</button>
<hr>
Simple method - using attributes
<input type='button' onclick='setAllFunc1()' value='set all to "getval()"'/>
<input type='button' onclick='setAllFunc2()' value='set all to "getvalNew()"'/>
<hr>
Better method - using addEventListener
<input type='button' onclick='setAllFunc3()' value='set all to "myFunc3()"'/>
</body>
</html>