简体   繁体   中英

changing links in an external function with Jquery

I have some links on a site which I need to direct to a page telling the user that they are leaving the site. All of these links already have an onClick function on them which normall triggers an alert telling them that they are leaving the site.
For example, this would normally trigger the alert:

<a href="http://www.example.com" onclick="return displayWarning(1, this);">Example</a>

What I'm trying to do is add functionality to that displayWarning() function so that if it is passed the integer '1' as a parameter, it takes the user to the new page such as: http://www.mySite.com/warning?url=http://www.example.com

Right now I'm using this:

if(msg == 0) {   
window.location.href='/warning?url='+($(this).href);  
}

I have also tried this to see if I could just change them all at load, but seem to be experiencing the same problem:

$(document).ready(function(){   
$("a[onClick='return displayWarning(1, this);']").attr('href', '/warning?url='+$(this).attr('href'));
}); 

However, url is not being properly defined as I'm fairly certain the the context of $(this) isn't set for the way that I'm trying to call it.

I've seen similar problems mentioned below but they don't seem to solve my issue as most of them are using either the class of the links or just changing all links to some value.

How to change the href for a hyperlink using jQuery jQuery attr href, why isn't it working?

Thanks.

我认为这是您想要的:

location.href='/warning?url='+encodeURIComponent(location.href);  

I can't understand what you're trying to achieve... why doesn't you just put an if in your displayWarning function using your already this as a parameter ?

function displayWarning(parameter, anchor){
    if(parameter == 1){
        $(anchor).attr("href", "http://example.com");
    }    
}

Thanks everyone but I ended up answering it. It turns out that there was already an object built into the function that I'm using (I didn't write it) that allowed me to grab the href value. I would, however, like to know if there is a faster way to do it.

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