简体   繁体   English

Jquery - 如何在链接中更改属性href的一部分?

[英]Jquery - How to change part of attribute href in link?

I don't know what I am doing wrong with changing href attribute in link from ?page to &page. 我不知道在从?page到&page的链接中更改href属性我做错了什么。 It stays on ?page. 它留在?页面上。 Thank you for any advice. 谢谢你的任何建议。

Jquery: jQuery的:

var article_pagination_change = function(){
    $('pagination a').each(function(){
       $(this).href.replace('?page','&page');
    });
}
article_pagination_change();

HTML: HTML:

<div id="pagination80" class="pagination" style="">
  <a class="first" data-action="first" href="?page=1">&lt;&lt;</a>
  <a class="previous" data-action="previous" href="?page=1">&lt;</a>
  <input class="pag_input_80" type="text" value="1 of 12" data-max-page="12" readonly="readonly">
  <a class="next" data-action="next" href="?page=2">&gt;</a>
  <a class="last" data-action="last" href="?page=12">&gt;&gt;</a>
</div>

You need to actually set the attribute: 您需要实际设置属性:

var article_pagination_change = function(){
    $('.pagination a').each(function(){
        var newurl = $(this).attr('href').replace('?page','&page');
        $(this).attr('href', newurl);
    });
}
article_pagination_change();

Note that I added the . 请注意,我添加了. before pagination and am using attr('href') instead of just href . pagination之前我使用attr('href')而不仅仅是href

Here's a working jsFiddle . 这是一个有效的jsFiddle

If you don't mind changing your code a bit more, you can try this simpler approach: 如果您不介意更多地更改代码,可以尝试这种更简单的方法:

var article_pagination_change = function(){
    $('.pagination a').attr('href',function(index,attr){
       return attr.replace('?','&');
    });
}
article_pagination_change();

You don't really need the .each() nor replacing ?page with &page unless you had extra ? 除非你有额外的东西,否则你真的不需要.each()也不需要用&page替换?page ? s on your href s... 在你的href s ...

Sample JSFiddle 示例JSFiddle

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

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