简体   繁体   中英

Defining function call dynamically with javascript to anchor tag

I have an anchor tag with id=1 and I am trying to define onClick="menu_function(shopname)" using the logic below, but it's not working like a.href :

function display_details(shopname,img)
{
    var a = document.getElementById("1");
    a.href = "./menu.php";
    a.onClick ="menu_function(shopname)";
}

Can you tell my why is it not working and guide me into the right direction?

Use a function expression as the value for onclick , not a string:

 function display_details(shopname,img)
 {
     var a = document.getElementById("1");
     a.href = "./menu.php";
     a.onclick = function(){
        menu_function(shopname);
     };
 }

Also note: JavaScript is case sensitive and the event is called onclick (lowercase) not onClick .

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