LoginSignup
1
3

More than 5 years have passed since last update.

URLパラメーターをJavascriptで取得してリンクの後ろに付けるメモ

Last updated at Posted at 2018-03-23

URLパラメーターをJavascriptで取得してリンクの後ろに付けるという事案が有りましてコーディングしてみたので、メモです。
・URL
✗✗✗✗✗✗.net/index.php?target=123456789

・HTML
(リンクタグ例)
<a href="✗✗✗✗✗✗.net/aaa/index.php?target=">リンク</a>

javascript

//コードが取得できないときのデフォルト値
var def = "123456789-1";//任意の値
var urlParam = location.search.substring(1);
if ((String(urlParam).length) <= 1){//単純にパラメーターが入っているかみてます。
    var cam = def;//入っていない場合、デフォルト値
}else{

if (urlParam.indexOf('target=') !== -1) {
//特定の文字が入っているかパラメーター精査を厳し目に

var parameter = decodeURIComponent(location.search.match(/target=(.*?)(&|$)/)[1]);
var str = parameter;
    var param = str.replace( '+', ',' );
//複数の値に対応。数値間の+(プラス)を,(カンマ)に置換
    var cam = param;
    var lang = 'default';
    var match = location.search.match(/target=(.*?)(&|$)/);
if(match) {
    lang = decodeURIComponent(match[1]);

}
}else{
    var cam = def;//条件に満たない場合デフォルト値の挿入
}

window.onload = function onLoad() {
        param = GetQueryString();
        target = document.getElementsByClassName('target');

function GetQueryString() {
var targets = document.querySelectorAll('a.target');//リンク挿入のClass
for (var i = 0; i < targets.length; i++) {
var target = targets[i];
var url = target.href;
url += cam;  //挿入するパラメーター
url += '$target2=';  //固定のものを入れるならこちらに記載★
target.href = url;  
}}
console.log(cam)
}

以上になります。
複数のLPを取り扱うときなどにあると便利かもですね!

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3