简体   繁体   中英

Assigning Anchor tag's to call Javascript function dynamically

I am creating list of <span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service">'+servicename+'</a><br/></span> tags dynamically and appending it to a div

Then using the below map to map a tags attribute to some function

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

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

This is the click Handler

$('#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);
}

Note : I am using Jquery v1.6.3

But when I click on any of the a tags, it calls the function an does all the operation inside the function, but gives an error Object dosen't support this porperty or method in the treeItemClickHandler function.

I would like to know,

  1. How to avoid getting this error?
  2. Is there a more better approach for something like this?
  3. And Is it 1st class functions that I am using (if so where can i learn more about it)?

Thanks.

Update

How can I pass 2nd parameter?

'<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);
}

It gives me infa9Service, undefined

check this out http://jsfiddle.net/ywQMV/4

1)define your functions.

2)define your id map.

html part :

<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 part:

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?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM