1

I have a script like:

<script  type="text/javascript">
     $("a.link").on("click",function(){
         window.open('http://site.com/fir.php','_self',false);
     });
</script>

and I am using it as

<a  href="fir.php" class="link">
fir
</a>

How can I make only one script and pass as variable the url I want to open?

3 Answers 3

3

You can use this.href to get the specific link's href to navigate to open in window but make sure to stop the link's default behavior with .preventDefault():

<script  type="text/javascript">
    $("a.link").on("click",function(e){
       e.preventDefault();// or return false; 
       window.open('http://site.com/'+this.href, '_self', false);
    });
 </script>
Sign up to request clarification or add additional context in comments.

Comments

2

Try like this

<script  type="text/javascript">
 $("a.link").on("click",function(){
     window.open('http://site.com/'+$(this).attr('href'),'_self',false);
 });
 </script>

You can use .prop also like

window.open('http://site.com/'+$(this).prop('href'),'_self',false);

2 Comments

you should use prop() instead of attr()
Yah ofcourse @Stiger we can use it...Thanks for your suggestion..I will update my ans
1

You can directly use this HTML code.May be it will helps you

 $(function(){
  $("a.link").on("click",function(e){
    window.open(this.href, '_self', false);
  });
 });

2 Comments

The whole point of the question is to avoid repeating the code for each link. How does this solve that?
$(function(){ $("a.link").on("click",function(e){ window.open(this.href, '_self', false); }); }); you can you this code then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.