質問

Here I am stuck with a scenario where I want to edit href of anchor tag before redirect. My scenario is if href attribute of anchor tag do not contain QueryString then append previous page query string to href means, suppose my current page url is xyz?x=2&y=4 Current href

href="local/services"

After Edit

href="local/services?x=2&y=4"

I tried.

HTML:

<a href="http://localhost/services" onclick="appendString(this)">test link </a> 

JavaScript

function appendString(obj) {
   var url = obj.getAttribute('href');
    if (url.indexOf('?') != -1)
      obj.setAttribute('href') = url + window.location.search;
    }

also tried

function appendString(obj) {
    var url = obj.getAttribute('href');
     if (url.indexOf('?') != -1)
         window.location.href =  url + window.location.search;
      }

but no success. Please suggest a solution. Thanks.

役に立ちましたか?

解決 2

Jed Burke pointed to your mistake. So you should use something like this:

function appendString(obj) {
    var url = obj.getAttribute('href');
    if (url.indexOf('?') != -1) obj.setAttribute('href', url + window.location.search);
}

or even simpler:

function appendString(obj) {
    if (obj.href.indexOf('?') != -1) obj.href += window.location.search;
}

他のヒント

The parameters for 'setAttribute' are incorrect.

element.setAttribute(name, value);

Courtesy MDN : Element.setAttribute

You can use JQuery for this:

$('.myLink').click(function() {
$(this).attr("href", this.href + "?param=1");
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top