简体   繁体   English

用网址字符串javascript中的变量替换锚标签href

[英]replace anchor tag href with variable from url string javascript

I have following java script code: 我有以下的Java脚本代码:

var product = getQueryVariable("product");

$('a.link').each(function()
{
    $(this).attr("href", $(this).attr("href") + "&product=" + getQueryVariable("product"));
});

function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);        

    var variables = query.split("&");

    for (var iCount = 0; iCount < variables.length; iCount++)
    {
        var pair = variables[iCount].split("=");

        if (pair[0] == variable)
            return pair[1];
    }
}

If url is: http://www.xxxx.com/index.htm?product=abc , It sets a link to an anchor tag 如果url为: http://www.xxxx.com/index.htm?product=abc ://www.xxxx.com/index.htm?product= http://www.xxxx.com/index.htm?product=abc ,它将设置指向锚标记的链接

<a class="link" href="http://www.aaaa.com/index.htm">Click here</a>

as

<a class="link" href="http://www.aaaa.com/index.htm?product=abc">Click here</a>

which is what I want, and it does it well. 这就是我想要的,并且做得很好。

But if anchor tag already has product variable in its href like 但是,如果定位标记在其href已经具有product变量,例如

<a class="link" href="http://www.aaaa.com/index.htm?product=xyz">Click here</a>

then I get 然后我得到

<a class="link" href="http://www.aaaa.com/index.htm?product=xyz&product=abc">Click here</a>

while I was expecting that if product variable is present in href of anchor tag, it will replace existing product variable. 而我期待,如果product变量存在于href锚标记,它将取代现有的产品变量。 And if there is no product variable in href tag, it will append it. 并且,如果href标记中没有产品变量,则会将其附加。

The code appends well, but does not replace existing product variable in href of anchor tag. 该代码可以很好地附加,但是不能替换锚标记的href的现有product变量。

So, the question is how do I get 'product' param from all a tags that have class 'link' ? 因此,问题是如何从所有具有'link'a标签中获得'product'参数? so that I can replace it in my code if found. 这样我就可以在代码中替换它(如果找到)。 And can I fetch it in $('a.link').each(function() ? 我可以在$('a.link').each(function()获取它吗?

How can I do it? 我该怎么做?

You can do something like this: 您可以执行以下操作:

function changeLinkQueries(link,parameter,replacedVal) {

  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = link.split('?')[1];
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
     var pair = vars[i].split("=");
     // If first entry with this name
     if (typeof query_string[pair[0]] === "undefined") {
       query_string[pair[0]] = decodeURIComponent(pair[1]);
       // If second entry with this name
     } else if (typeof query_string[pair[0]] === "string") {
       var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
       query_string[pair[0]] = arr;
       // If third or later entry with this name
     } else {
       query_string[pair[0]].push(decodeURIComponent(pair[1]));
     }
  } 

  var queries = query_string,
    linkArr = [];
  queries[parameter] = replacedVal;

  for(query in queries){
    linkArr.push(query + '=' + queries[query]);
  }

  return link.split('?')[0] + '?' + linkArr.join('&');

};

The function usage is : changeLinkQueries(link,parameter,replacedVal) : 该函数的用法是: changeLinkQueries(link,parameter,replacedVal)

  • link : is the link that you want to modify link:是您要修改的链接
  • parameter: the parameter you want to change 参数:您要更改的参数
  • replacedVal: the value that you want to replace with it replaceVal:您要替换的值

Example: changeLinkQueries('http://www.aaaa.com/index.htm?product=xyz','product','test') returns ==> http://www.aaaa.com/index.htm?product=test 示例: changeLinkQueries('http://www.aaaa.com/index.htm?product=xyz','product','test')返回==> http://www.aaaa.com/index.htm?产品=测试

Add this function to your code and update your code to : 将此功能添加到代码中,并将代码更新为:

var product = getQueryVariable("product");

$('a.link').each(function(){
    $(this).attr("href", changeLinkQueries($(this).attr("href"),'product',getQueryVariable('product')));
});

function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);        

    var variables = query.split("&");

    for (var iCount = 0; iCount < variables.length; iCount++)
    {
        var pair = variables[iCount].split("=");

        if (pair[0] == variable)
            return pair[1];
    }
}

Try this, 尝试这个,

Array.prototype.contains = function(x){
  return this.indexOf( x ) > -1 ? true : false;
}

var getUrlVars = function(url){
    var vars = [], hash;
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
        vars.push(decodeURIComponent(hash[0]));
        vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
     }
     if(vars[0] == url){
        vars =[];
     }
     return vars;
}


var getUrl = function(url){
    var urlParams = getUrlVars(window.location.href),
        linkParams = getUrlVars(url),
        altered = false;

    for(i = 0; i < linkParams.length; i++){
        var t = linkParams[i];
        if(urlParams.contains(t)){
            linkParams[t] = urlParams[t];
            altered = true;
        }
    }
    return altered ? url.split("?")[0] + "?" + linkParams.map(function(y){return y + "=" + linkParams[y]}).join("&") : url;
}

$("a.link").each(function (i,link) {
    link.attr("href",getUrl(link.attr("href")));
})

Try this 尝试这个

$('a.link').each(function()
{
    $(this).attr("href", $(this).attr("href").split("product=")[0] + "product=" + getQueryVariable("product"));
});

This works with links already containing product value

This code worked: 此代码有效:

$('a.link').each(function()
{
    var anchor_url = $(this).attr("href");
    var product_val = '';

    if (-1 == anchor_url.indexOf('&product='))
    {
        if (-1 == anchor_url.indexOf('?product='))
            product_val = anchor_url.substr(anchor_url.indexOf('?product=')+'?product='.length);
    }
    else
        product_val = anchor_url.substr(anchor_url.indexOf('&product=')+'&product='.length);

    if (product_val.indexOf('&') != -1) product_val = product_val.substr(0, product_val.indexOf('&'))

    if (product_val == '') new_link = anchor_url+'&product='+getQueryVariable("product");
    else new_link = anchor_url.split(product_val).join(getQueryVariable("product"));

    $(this).attr("href",  new_link);
});

i hope this will help, 我希望这个能帮上忙,

$(this).attr("href", getQueryVariable($(this).attr("href"), "product"));

function getQueryVariable(hrefLink, variable)
{
    if(hrefLink.contains("product")){
        return hrefLink;
    }else{
        //write your code here and return full url

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM