Add query string to URL with jQuery

What am I doing wrong?

  • Only on pages with the URL "/MyWebsite/Example.aspx" add "? Template = PW"
  • But only for links containing "/HelloWorld/default.aspx"

There is no identifier or classes associated with this link, so I have to look for the URL.

This is my code, but the links are not updating .. I know that I am near!

$(document).ready(function(){ if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0) { $('a[href*="/HelloWorld/default.aspx"]').append("href",$("?template=PW")) } }); 
+4
source share
5 answers
 $(document).ready(function(){ if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0) { var $el = $('a[href*="/HelloWorld/default.aspx"]'); $el.attr("href", $el.attr("href")+ "?template=PW"); } }); 
+4
source

Use the $ .attr () parameter to edit the attribute.

$. append () is used to insert the html node child element inside your element.

 $(document).ready(function(){ if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0) { var href = '/HelloWorld/default.aspx'; $('a[href*="' + href + '"]').attr("href", href + "?template=PW") } }); 
+3
source

Replace

 $('a[href*="/HelloWorld/default.aspx"]').append("href",$("?template=PW")) 

WITH

 $.each( $('a[href*="/HelloWorld/default.aspx"]'), function(index, value) { $(value).attr('href', $(value).attr('href') + '?template=PW'); } ); 

This will help you get started, but you should also check to see if the query string parameter is already in the agreed URL.

$ (). append () does not change the value of the href attribute, it is used to insert content at the end of each matching element. The jQuery documentation contains examples of using $ (). Append ().

+1
source

Do you consider using PURL ? With PURL, I was able to do this:

 var url = "http://localhost/some/url?item1=one&item2=two"; if ($.url(url).attr('query')) { url = url + '&newItem=new'; } else { url = url + '?newItem=new'; } 
+1
source

This will definitely solve your problem as well as mine.

 <script type="text/javascript"> var querystring = 'MyString'; // Replace this $('a').each(function(){ var href = $(this).attr('href'); href += (href.match(/\?/) ? '&' : '?') + querystring; $(this).attr('href', href); }); </script> 
+1
source

Source: https://habr.com/ru/post/1479448/


All Articles