开发者

Reassign onclick for anchor tag

开发者 https://www.devze.com 2022-12-21 07:51 出处:网络
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.

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.wikipedi开发者_运维知识库a.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.


Don't forget to return false in 'onclick', or browser will handle click and open link in 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! 

});
0

精彩评论

暂无评论...
验证码 换一张
取 消