简体   繁体   English

在JavaScript或jQuery中的href属性中替换冒号

[英]Replace colon in href attribute in JavaScript or jQuery

I have a problem handling IDs with a colon in jquery. 我在jquery中用冒号处理ID时遇到问题。 If there is a colon in an ID the smooth scroll doesn't work. 如果ID中有冒号,则无法平滑滚动。

The HTML HTML

<a href="#fn:1">Go to Footnote 1</a>

<div id="fn:1>Lorem ipsum Bla Bla</div>

JS JS

  var $root = $('html, body');
  $('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top
    }, 400, function () {
        window.location.hash = href;
    });
    return false;
});

Do this: 做这个:

$(function(){
    $('[href]').each(function(){
        $(this).attr('href',$(this).attr('href').replace(/:/g,""));
    });
});

That will remove : from all href 这将删除:从所有href

Try this. 尝试这个。

var $root = $('html, body');
  $('a').click(function() {
    var href = $.attr(this, 'href'),
        href = href.split(':'),
        href = href.join('\\:');
      alert(href)
    $root.animate({
        scrollTop: $(href).offset().top
    }, 400, function () {
        window.location.hash = href;
    });
    return false;
});

Demo Fiddle 演示小提琴

You need to replace # with \\\\# and : with \\\\: to escape the character and to make it work: 您需要替换#\\\\#:\\\\:逃跑的角色,并使其工作:

var $root = $('html, body');
  $('a').click(function() {
      var href = $.attr(this, 'href').replace(/:/g,"\\\\:");
      href = href.replace(/#/,"\\\\#");
    $root.animate({
        scrollTop: $(href).offset().top
    }, 400, function () {
        window.location.hash = href;
    });
    return false;
});

See more about escaping the character here 此处查看有关转义角色的更多信息

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

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