开发者

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="ret开发者_如何学Pythonurn 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.


I think this is what you want:

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜