Add link binding with jquery

I am new to javascript. You must remove any existing bindings (for example: # page 33), add other bindings (for example: # page1) to all links in the list dynamically (on the client side) using javascript or jquery:

Initial html (from server):

<ul id="lang_menu"> <li><a href="home.php?lang=eng#page33">English</a></li> <li><a href="home.php?lang=tam#page33">Tamil</a></li> <li><a href="home.php?lang=sin#page33">Sinhala</a></li> </ul> 

this should behave like (replace # page33 with # page1 on the client side):

 <ul id="lang_menu"> <li><a href="home.php?lang=eng#page1">English</a></li> <li><a href="home.php?lang=tam#page1">Tamil</a></li> <li><a href="home.php?lang=sin#page1">Sinhala</a></li> </ul> 

Here I need it Website Development

Please help me. Thanks in advance...

+4
source share
2 answers

Try as follows: -

 $(function () { $('#lang_menu li a').attr('href', function (_, oldHref) { return oldHref + "#page1"; }); }); 

Demo

For your updated question, you can try something like this:

using regex to replace #part with a url.

 $(function () { $('#lang_menu li a').attr('href', function (_, oldHref) { oldHref = oldHref.replace(/\#(.*)/g, "#page1"); if(oldHref.indexOf('#') == -1) oldHref += "#page1"; return oldHref; }); }); 

Demo2

+5
source

If you are dealing with a large number of DOM elements, it is less expensive to add an anchor lazily.

 jQuery("a").bind("click", function(e) { e.preventDefault(); document.location = jQuery(this).attr("href") + "#page1"; }); 
+3
source

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


All Articles