jquery implements smooth scrolling, using string with pure code in id causes error

Asked 2 years ago, Updated 2 years ago, 89 views

It implements smooth scrolling using jquery.
Here's the code:

$(function(){
    $('a[href^="#"]').click(function(){
        var speed = 400;
        var href=$(this).attr("href");
        var target=$(href=="#"||href==""?'html':href);
        var position = target.offset().top;
        $("html, body").animate({scrollTop:position}, speed, "swing");
        return false;
    });
});

This is what the html file looks like.

<a href="#no_%e6%97% a5%e6%9c%ac%e8%aa%9e">h2
<h2id="no_%e6%97% a5%e6%9c%ac%e8%aa%9e">Go here</h2>

It can be moved, but javascript has an error and does not scroll smoothly.

The errors are as follows:

Error: Syntax error, uncognized expression: # no_%e6% 97% a 5% e6% 9c% ac%e8% aa%9e

Can't you scroll smoothly with an id mixed with pure code like this.
Please let me know if there is a solution.

jquery

2022-09-30 21:46

1 Answers

It can be moved, but javascript has an error and does not scroll smoothly.
Can't you scroll smoothly with an id mixed with pure code like this.
Please let me know if there is a solution.

The URI specification is '#no_%e6%97% a5%e6%9c%ac%e8%aa%9e' (#no_Japanese UTF8 expression) is
There should be no problem, but
Isn't the % encoded ID specification in the HTML tag incorrect?

Enter your ID in Japanese and url-encoded URL.

<a href="#no_%e6%97% a5%e6%9c%ac%e8%aa%9e">h2
<h2id="no_Japanese">Go here</h2>

JavaScript url Decodes and Find IDs

var href=decodeURI($(this).attr("href"));

Then, I was able to confirm that it works with chrome and edge.


2022-09-30 21:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.