2011-11-23 52 views
0

我动态创建的<span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service">'+servicename+'</a><br/></span>标签列表并将其附加到一个div勘定锚标签的调用JavaScript函数动态

然后使用下面的地图,地图a标签属性的一些功能

var idMap = { 
      //it can be a lot more 
      "javaInfo":javaInfo, 

      /*infa9 product map*/ 
      "infa9PMServer":infa9PMServer, 
      "infa9Service":infa9Service 
     }; 

这是单击处理

$('#ds-accordion a').click(function(event) { 
    var elementId=$(this).attr("id"); 
    treeItemClickHandler(elementId); 
}); 

function treeItemClickHandler(id) 
{ 
    (idMap[id])(id); //Is this usage called 1st class functions? 
} 

function infa9Service(id) 
{ 
    alert("i got this "+id); 
} 

注意:我使用jQuery 1.6.3版本

但是,当我点击a标签中的任何一个时,它会调用函数an并执行函数中的所有操作,但在treeItemClickHandler函数中给出错误Object dosen't support this porperty or method

我想知道,

  1. 如何避免这个错误?
  2. 有没有更好的方法来解决这个问题?
  3. 是我使用的第一类功能(如果是的话,我可以在哪里了解更多)?

谢谢。

更新

我怎样才能通过第二个参数?

'<span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service" title='+servicename+'>'+servicename+'</a><br/></span>' 

$('#ds-accordion a').click(function(event) { 
    var elementId=$(this).attr("id"); 
    var elementName=$(this).attr("title"); 
    treeItemClickHandler(elementId,elementName); 
}); 

function treeItemClickHandler(id,name) 
{ 
    idMap[id](id,name); 
} 

function infa9Service(id,name) 
{ 
    alert(id+", "+name); 
} 

它给了我infa9Service, undefined

+1

目前尚不清楚你要完成的任务。这听起来像你有一个每个元素ID的函数。为什么不直接使用该函数作为点击处理程序?元素标识必须是唯一的。你是否对多个元素使用相同的ID? – gilly3

+0

函数是否在与idMap相同的作用域中定义?将'alert(id)'或'console.log(id)'作为'treeItemClickHandler'的第一行,并确认您获得了您期望的id值。如果你在那个时候得到一个有效的ID,我希望它能工作。 ''(idMap [id])'不需要括号,但它应该可以使用或不使用它们。 – nnnnnn

+0

@ gilly3:同样的id也是允许的,因为我还需要传递2个参数'id'和'servicename',所以只要它是相同的函数,它就会根据'servicename'来区分。由于有很多功能,我认为这张地图是一个简单的方法来跟踪所有的功能 – abi1964

回答

1

检查了这一点http://jsfiddle.net/ywQMV/4

1)定义的功能。

2)定义你的id地图。

HTML的一部分:

<div id ="ds-accordion">  
    <span class="infa9span"> 
     <img src="/csm/view/include/images/foldericon.png"/> 
     <a id="infa9Service" title='+servicename+'>'+servicename+'</a> 
     <br/> 
    </span> 

JS部分:

function infa9Service(id, serviceName) 
{ 
    alert("i got this "+id +" serviceName : " + serviceName); 
} 


var idMap = { 
      "infa9Service":infa9Service 
     }; 

$('#ds-accordion a').click(function(event) { 
    var elementId=$(this).attr("id"); 
    var serviceName = this.title; 
    treeItemClickHandler(elementId, serviceName); 
}); 

function treeItemClickHandler(id,serviceName) 
{ 
    // alert(idMap[id]) 
    (idMap[id])(id,serviceName); //Is this usage called 1st class functions? 
} 
+0

为什么你必须先定义函数?函数语句被挂起... – nnnnnn

+0

@erimerturk:没关系,我怎么能通过'servicename'这些函数,就像在传递2参数? – abi1964

+0

我更新它,再次检查它。 – erimerturk