Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

firefox - What characters are allowed in jQuery selectors?

I'm am using jQuery to smooth scroll to some anchors on my website. The anchors are created programmatically so that they can contain some german umlauts like ?ü, ?, ?? or other unicode characters like ??,è? etc.. The function uses the hash to select the element the hash is referring to:

// Smooth scroll to anchor position.
function smoothScroll (hash) {

  var scrollTo = typeof $(hash).offset().top != undefined ? $(hash).offset().top: 0;

  $('html, body').animate({
    scrollTop: scrollTo

  }, 800);
}

// Test smooth scroll.
smoothScroll ("#Akademie-für-Gestaltung");

This works in Chrome and Safari, but not in Firefox. It produces the following error:

Error: Syntax error, unrecognized expression: #Akademie-f%C3%BCr-Gestaltung...

This brings me to my question. How do I know, which characters are allowed in jQuery selectors? The jQuery documentation mentions only the following characters !"#$%&'()*+,./:;<=>?@[]^{|}~

And how do I have to escape other characters, to make sure the selectors will work in all modern browser?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How do I know, which characters are allowed in jQuery selectors?

They're CSS selectors. All the details are in the selectors specification. The rules for literal IDs and class names used in selectors are here. Escaping lets you use characters you couldn't use literally (but it's a pain, so best to avoid). So for instance, while you can use ü, doing so is a pain because you can't use it literally, you have to escape it.

But ID selectors are just a special (quite fast) kind of selector. You can use an attribute selector in quotes, which means you can avoid escaping: $('[id="Akademie-f%C3%BCr-Gestaltung"]') That's perfectly valid and correct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...