简体   繁体   中英

Reassign onclick for anchor tag

I have a problem with <a> tags.

I need to reassign an onclick event to this tag, but the href attribute must contain a link.

For example, I have some link:

<a href="http://en.wikipedia.org">Wikipedia</a>

And i need to change only the onclick event for this link so that when I click on it, some JavaScript function is called.

不要忘记在“ onclick”中返回false,否则浏览器将处理href中的单击并打开链接。

<a href="http://en.wikipedia.org" onclick="yourfunction(this); return false;" >Wikipedia</a>

Not sure what you mean, but try this:

$(function() {
    // Find all links pointing to wikipedia
    $("a[href*='wikipedia.org']").click(function() {
        // Do something
        return false; // to prevent the link from actually going to wikipedia
    });
});

but href attribute must contain a link

If you provide a link then the page will be redirected there, so you might want to do this:

<a href="#" onclick="func1();func2();redirect('url');">Wikipedia</a>

This makes sure that you perform your functions first and finally redirect function to redirect the page to the url you specify.

The simplest way would be to give your link an id, ie

<a href="http://wikipedia.org" id="myLink">Whatever</a>

Then simply assign an onclick via jquery like so:

$("a#myLink").click(function() {
   //Go wild! 

});

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