我想在重定向页面后调用一个函数。
在我的函数中,我放了一个ID参数,但当我检查控制台时,它不会显示。我知道我可以通过点击事件运行它,但我不会从上一页获得ID参数。
有办法完成吗?
代码:
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
}
我同意Katana的评论。重定向语句之后的任何内容都不会运行,因为页面本身正在重定向。我建议仍然获取item_id并绕过这个障碍的一种方法是将item_id作为参数包含在重定向url中。然后在新页面上,解析url中的参数并保存item_id。
Cory Laviska关于用Javascript解析URL的文章中的一个很好的例子展示了如何从URL中获取单个参数。
建立在Manish的答案之上:
当前页面上的功能:
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url+'?saved_item_id='+item_id; // new url
});
}
REDIRECTED页面上的功能(假设您只有一个参数)
$( document ).ready(function() {
var url = $(this).data('url');
var item_id = url.queryKey['saved_item_id'];
save(item_id);
});
它可能需要一些tweeks,因为我没有测试代码,但希望它能让你走上正轨。:)
希望这能有所帮助。如果它有助于和/或回答您的问题,请选择作为答案并向上投票!:D如果您有任何问题,请随时通知我
试试这个
容器是页面中执行操作的部分。
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
$("#container").load(url,function(){
// other stuffs and functionalities
save(item_id); // call function after new url finish loading
});
});
}
您可以尝试这样的方法。
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url+'?saved_item_id='+item_id; // 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
}*/
此外,在新的重定向URL上,您可以获得在上一页中附加到URL的item_id。
希望这能有所帮助。