Append urlVariable to next page's link

一曲冷凌霜 提交于 2019-12-13 04:06:11

问题


How do i set a page to append a urlVariable into its links?

for example, i have 3 different pages and all are linked into the same page, e.g.
receiver.html

first page link:

receiver.html?sender=1

second page link:

receiver.html?sender=2

third page link:

receiver.html?sender=3

when the first page is clicked it will send the user to receiver.html which has many outgoinglinks inside, and the script will append the variable into all its outgoing links depending on the three pages above?

receiver.html

outgoinglink.html?sender=1
outgoinglink2.html?sender=1
outgoinglink3.html?sender=1

and if second page is used, the receiver.html will append

?sender=2

on all its link inside and so on and so forth..


回答1:


Well you could use the function shown in this post (http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript) to get your parameter

function getParameterByName( name )

    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }

var sender = getParameterByName('sender');

then attach what you need to all href:

$('a').each(function(){
    var href = $(this).attr('href');
    if (href.indexOf('&') !== -1){
        //if you have on & in the href you must use &
        $(this).attr('href', href+'&sender='+sender);
     }else{
        $(this).attr('href', href+'?sender='+sender);
     }
});


来源:https://stackoverflow.com/questions/6537820/append-urlvariable-to-next-pages-link

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!