javascript通过函数调用函数的问题
对几个标签添加鼠标点击事件:
// tool functions
function $(id)
{
return document.getElementById(id);
}
function addEventListener(element,event,listener)
{
if(element.addEventListener){
element.addEventListener(event,listener,false);
return true;
}
else if(element.attachEvent){
element.attachEvent('on' + event,listener);
return true;
}
return false;
}
function addDiv(event)
{
}
function delDiv(event)
{
}
function changeDiv(event)
{
}
function beginDiv(event)
{
}
function stopDiv(event)
{
}
// add events
var add = $('add');
var del = $('del');
var change = $('change');
var begin = $('begin');
var stop = $('stop');
if(add) {addEventListener(add,'click',addDiv);}
if(del) {addEventListener(del,'click',delDiv);}
if(change) {addEventListener(change,'click',changeDiv);}
if(begin) {addEventListener(begin,'click',beginDiv);}
if(stop) {addEventListener(stop,'click',stopDiv);}
我现在想将add events 部分修改一下,使用字符串拼凑出回调函数名,如add的回调函数的名字为add+'Div', 但是现在我怎么传到addEventListener中? 如下面代码的注释出如何写?
AKA日天
12 years, 5 months ago
Answers
我给你改过的,测试能通过
<script language="javascript">
function $(id){
return document.getElementById(id);
}
window.onload = function(){
var arr = ['add','del','change','begin','stop'];
for (var i in arr){
var tmp = $(arr[i]);
obj = new Object();
obj.name = arr[i];
if(tmp){
addEventListener(tmp, 'click', attachEvent, obj);
}
}
}
function attachEvent(e){
var fun = this.name + 'Div()';
eval(fun);
}
function addEventListener(element,event,listener, args){
var eventHander = listener;
if(args){
eventHander = function(e){
listener.call(args, e);
}
}
if(element.addEventListener){
element.addEventListener(event,eventHander,false);
}else if(element.attachEvent){
element.attachEvent('on' + event,eventHander);
}
}
function addDiv(event){
alert('add');
}
function delDiv(event){
alert('del');
}
function changeDiv(event){
alert('change');
}
function beginDiv(event){
alert('begin');
}
function stopDiv(event){
alert('stop');
}
</script>
柒世纪饭饭
answered 12 years, 5 months ago