call javascript function on hyperlink click

前端 未结 9 1940
陌清茗
陌清茗 2020-11-30 21:13

I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?

9条回答
  •  一向
    一向 (楼主)
    2020-11-30 21:53

    Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.

    Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:

    [c# example only probably not the way you're writing out your js]
    Response.Write("My Link");
    
    [Javascript]  
    document.getElementById('uxAncMyLink').onclick = function(e){
    
    // do some stuff here
    
        return false;
        }
    

    That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.

    Hope that is of use.

提交回复
热议问题