jQuery选择器允许哪些字符? [英] What characters are allowed in jQuery selectors?

查看:57
本文介绍了jQuery选择器允许哪些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery平滑滚动到我网站上的某些锚点.锚是通过程序创建的,因此它们可以包含诸如»ü,ä,ö«之类的德语变音符号,或诸如»ß,è«等其他Unicode字符. 该函数使用哈希来选择哈希所指的元素:

// 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");

这在Chrome和Safari中有效,但在Firefox中无效.它产生以下错误:

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

这使我想到了我的问题.我怎么知道,jQuery选择器允许哪些字符? jQuery文档仅提及以下字符!"#$%&'()*+,./:;<=>?@[\]^{|}~

我该如何转义其他字符,以确保选择器在所有现代浏览器中都能正常工作?

解决方案

我怎么知道jQuery选择器允许哪些字符?

它们是CSS选择器.所有详细信息都在选择器规范中.选择器中使用的文字ID和类名称的规则是此处.转义使您可以使用原本无法使用的字符(但这很痛苦,因此最好避免使用).因此,例如,尽管您可以使用ü,但是这样做很麻烦,因为您不能按字面意义使用它,而必须对其进行转义.

但是ID选择器只是一种特殊的(非常快的)选择器.您可以在引号中使用属性选择器,这意味着您可以避免转义:$('[id="Akademie-f%C3%BCr-Gestaltung"]')这是完全正确和正确的.

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?

解决方案

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.

这篇关于jQuery选择器允许哪些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆