简体   繁体   English

单击按钮后更改部分URL

[英]Change part of url after button click

i have following Situation: Two Categories and one list of links. 我有以下情况:两个类别和一个链接列表。

Now i Need to Change a part of the URL, according to the category. 现在,我需要根据类别更改URL的一部分。 Used therefore 2 Buttons, to Switch between the categories. 因此使用2个按钮在类别之间切换。 Category A is Default. 类别A为默认值。

<button id="Tab1">CategoryA</button>
<button id="Tab2">CategoryB</button>

<a id="link" href="http://www.test.com/CategoryA/Type1" target="_blank">Type1</a>
<a id="link" href="http://www.test.com/CategoryA/Type2" target="_blank">Type2</a>
<a id="link" href="http://www.test.com/CategoryA/Type3" target="_blank">Type3</a>

Inside the URL structure only the Category Part should differ, according to which button was clicked. 在URL结构中,根据单击的按钮,仅类别部分应该有所不同。 The URL change hast to happen immediately, so I thought to do it with javascript. URL更改不必立即发生,因此我想使用javascript来完成。

Tried Stuff like 尝试过的东西像

$('#Tab1').on ('click', function (e) {
      link.href.replace.... 

but had no luck with it. 但没有运气。

Would be nice if some could help 如果有人可以帮助的话会很好

You seem to be using jQuery, so here is a jQuery solution. 您似乎正在使用jQuery,因此这里是jQuery解决方案。

You can use jQuery's .each() to loop through each link, get the href , replace the category and then set the new href . 您可以使用jQuery的.each()遍历每个链接,获取href ,替换类别,然后设置新的href

You should note that you cannot have repeating id s so I have changed them to classes. 您应该注意,您不能重复id因此我将其更改为class。 Here's the code. 这是代码。

$('#Tab1').on('click', function (e) {
    $( ".link" ).each(function( index ) {
        var newLink=$(this).attr("href").replace("CategoryB","CategoryA");
        $(this).attr("href", newLink);
    });
});

$('#Tab2').on('click', function (e) {
    $( ".link" ).each(function( index ) {
        var newLink=$(this).attr("href").replace("CategoryA","CategoryB");
        $(this).attr("href", newLink);
    }); 
});

and here's the updated html code, just with the ids changed to classes. 这是更新的html代码,只是将id更改为class。

<button id="Tab1">CategoryA</button>
<button id="Tab2">CategoryB</button>

<a class="link" href="http://www.test.com/CategoryA/Type1" target="_blank">Type1</a>
<a class="link" href="http://www.test.com/CategoryA/Type2" target="_blank">Type2</a>
<a class="link" href="http://www.test.com/CategoryA/Type3" target="_blank">Type3</a>

Here's a jsfiddle showing it working: http://jsfiddle.net/QaJS9/1/ 这是一个显示其工作原理的jsfiddle: http : //jsfiddle.net/QaJS9/1/

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

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