简体   繁体   中英

do general script for links with javascript

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?

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>

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);

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);
  });
 });

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