call javascript function on hyperlink click

前端 未结 9 1933
陌清茗
陌清茗 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:40

    The simplest answer of all is...

    <a href="javascript:alert('You clicked!')">My link</a>

    Or to answer the question of calling a javascript function:

    <script type="text/javascript">
    function myFunction(myMessage) {
        alert(myMessage);
    }
    </script>
    
    <a href="javascript:myFunction('You clicked!')">My link</a>

    0 讨论(0)
  • 2020-11-30 21:40

    The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:

    <div class="menu">
        <a href="http://example.org">Example</a>
        <a href="http://foobar.com">Foobar.com</a>
    </div>
    
    <script>
    jQuery( 'div.menu a' )
        .click(function() {
            do_the_click( this.href );
            return false;
        });
    
    // play the funky music white boy
    function do_the_click( url )
    {
        alert( url );
    }
    </script>
    
    0 讨论(0)
  • 2020-11-30 21:42

    I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.

    <a href='#' onclick='jsFunction();alert('it works!');'>Link</a>

    It could be also used on input tags eg.

    <input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>

    0 讨论(0)
  • 2020-11-30 21:43

    I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.

    attachEvent / addEventListening allow multiple event handlers to be created.

    0 讨论(0)
  • 2020-11-30 21:44

    With the onclick parameter...

    <a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
    
    0 讨论(0)
  • 2020-11-30 21:48

    Use the onclick HTML attribute.

    The onclick event handler captures a click event from the users’ mouse button on the element to which the onclick attribute is applied. This action usually results in a call to a script method such as a JavaScript function [...]

    0 讨论(0)
提交回复
热议问题