Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

javascript - Execute a function after changing location.href

I want to call a function after redirecting the page.

Inside my function I put a parameter which is an ID but when I check the console it wont display. I know I can be able to run it via on click event but I wont get the ID param from the previous page.

Is there a way to get it done?

Code:

function encode(item_id){
  $('.js-encode').click(function(){
    var url = $(this).data('url');
    location.href = url; // new url
    save(item_id); // call function after new url finish loading
  });
}

function save(item_id){
  console.log(item_id); // check if there's item_id exists
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I agree with Katana's comment. Anything after your redirect statement will not run because the page itself is redirecting. One way that I would suggest to still get the item_id and get around that barrier, would be to include the item_id in the redirect url as a parameter. Then once on the new page, parse that parameter out of the url and save the item_id.

A great example from Cory Laviska's article on Parsing URLs in Javascript, shows how you can get the individual parameters from a URL.

Building onto Manish' answer:

Function on the current page:

function encode(item_id){
    $('.js-encode').click(function(){
    var url = $(this).data('url');
    location.href = url+'?saved_item_id='+item_id; // new url
    });
}

Function on the REDIRECTED Page (assuming you only have one parameter)

$( document ).ready(function() {
     var url = $(this).data('url');
     var item_id = url.queryKey['saved_item_id'];
     save(item_id);
 });

It may need a few tweeks because I didn't test the code, but hopefully it'll get you on the right track. :)

Hopefully this helps. If it helps and/or answers your question, please select as answer and up vote! :D Feel free to let me know if you have any questions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...