Search code examples
javascriptjqueryexecutionprefixmultiple-instances

Prefixing a URL in an window.open function jQuery


I have this HTML:

<a href="#" onclick="window.open('TrackPackage.asp?ID=4', '', 'settings');">Track Your Package »</a>

Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:

$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});

However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...

The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.

I hope I've been clear and you can help me. Thanks.


Solution

  • Why are you doing the click even inline like that? I would just output the links like:

    <a href="/path/to/file.html" target="_blank">Link Text</a>
    

    And then:

    $('a[target=_blank]').click(function(){
       var prefix = 'http://domain.com';
       window.open(prefix + $(this).attr('href'));
    });