简体   繁体   中英

JQuery load a page in background

I have a few menutabs in my website. When the user clicks on one, it expands or hides, but when it does a page is loaded (in the background) to save the way he wants (without refresh).

I'm using this:

function ajaxLink(){
var age = $("#age").val();
$.get("<?php echo _SITE_ADDRESS; ?>/linktab/1",{"age":age},function(r){   });
}

It's not meant for this but it works for a single tab; if I want to add more tabs then I have to add more of these and change the function name and in a href I have to add onclick="ajaxLink()" .

(The age var is there for no reason. I can't get it out without breaking the code.)

How can I change this to make it a single jQuery so when a user clicks on a tab with id=1 it goes /linktab/1 , tab with id=2 it goes /linktab/2 , and so on.

Thanks

If I were you the first step I'd take is to add a class to all the elements that you want to use to trigger this function(the things you click on). You can remove the onClick from them. Give them all class "ajaxLink" or whatever you prefer. Also give them an id, the number of the tab. For example:

<div class="ajaxLink" id="2"></div>

$('.ajaxLink').click(function(event){
    ajaxLink(event.target.id);
});

function ajaxLink(id){
    var age = $("#age").val();
    $.get("<?php echo _SITE_ADDRESS; ?>/linktab/"+id,
        {"age":age},function(r){   });
}

From what I understand from your question, if your previous code works this should too. If not let me know what error you are getting.

If you are using jquery, you should use it to bind the event. Let's suppose this html:

<ul>
  <li class=tab><a href="<?php echo _SITE_ADDRESS; ?>/linktab/1">tab 1</a>
  <li class=tab><a href="<?php echo _SITE_ADDRESS; ?>/linktab/2">tab 2</a>
</ul>

You can bind your ajaxLink to both of them using

$('.tab a').on('click', function(event){ // Using an anonymous function instead of ajaxLink
  event.preventDefault(); // Cause you don't want to activate the link

  var age = $("#age").val();

  // "this" refers to the A element

  var url = this.href;
  $.get(url,{"age":age},function(r){ /* your callback */  });

});

Got it to work myself with just this.

function ajaxLink(id){
var id = event.target.id;
$.get("<?php echo _SITE_ADDRESS; ?>/linktab/"+id);
}

and in each "a hreaf" I used onclick="ajaxLink()" id="1 changing the id for each menu tab.

Thanks

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