jquery中的特殊字符
我有一个 div 列表,每个 div 都有一个 id。 id 还充当链接:"http://en.wikipedia.org/wiki/" + id
是 wikipedia 上此项目的链接,"/image/" + id + ".jpg"
是该项目的本地图像。
但我有一些带有特殊字符的 id。有两种类型(我发现有错误):第一种是 A_(B)
,包含括号,第二种是 A%C3%A9B
(AéB),包含特殊字母。我知道 ()
可以用 %28%29
代替,所以它基本上只是一种类型。我已经测试过,这种名称适用于图像和维基链接。
问题是,当我使用 jQuery 时,$('#' + id)
无法找到那些带有特殊字母的对象。任何人都知道如何处理它?
I have a list of div, each has an id. The id also performs as a link: "http://en.wikipedia.org/wiki/" + id
is the link to this item on wikipedia, "/image/" + id + ".jpg"
is the local image for this item.
But I have some id with special characters. There are two types (that I found have bug): first, A_(B)
, containing parentheses, second A%C3%A9B
(AéB), containing special letter. I know ()
can be replaced by %28%29
, so it is basically only one type. And I have tested, this kind of name works for image and wiki link.
The problem is, when I use jQuery, $('#' + id)
cannot find those objects with special letters. Anyone has any idea how to deal with it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您查看 选择器 页面的第二段,它会显示这些字符
!"#$%&'()*+,./:;<=>?@[\]^``{|}~
使用时需要转义。但是如果你是包括其他字符,最好使用它们的转义码包含它们(Google 闭包编译器会自动为您执行此操作)。 é 可以替换为
\u00e9
If you look at the second paragraph of the selectors page, it shows you that these characters
!"#$%&'()*+,./:;<=>?@[\]^``{|}~
need to be escaped when used.But if you are including other characters it might be best to use their escape code to include them ( google closure compiler will automatically do this for you ). So this letter
é
can be replaced with\u00e9
您是否尝试过:
看看是否能解决问题?
have you tried:
to see if it resolves it?
有关详细信息,请参阅这个问题。
就我个人而言,我认为 ID 应该符合人类可读、易于理解的 ID。考虑使用不同的机制附加 URL,例如 jQuery 的
$.data
或其他没有有效性限制的属性。See this SO question for more info.
Personally, I believe IDs should conform to human-readable, easily-understandable IDs. Consider attaching URLs using a different mechanism, like jQuery's
$.data
, or another property that doesn't have validity restrictions.一个好的经验法则是首先符合相关规范。根据 HTML 4.01:
因此元素 ID 或名称中不允许使用 (, ) 和 % 等字符。
id 中的不一致字符可能会导致 jQuery 以外的问题。使用encodeURIComponent(例如,将 ( 替换为 %28) 没有帮助,因为也不允许使用 % 字符。但是您可以使用典型 az,AZ 范围之外的字母的字符实体,或者您可以只使用普通的旧 document.getElementById 并且如果您确实需要使用 jQuery:
可能就足够了(但不可靠)。
A good rule of thumb is to first conform to relevant specifications. According to HTML 4.01:
So characters like (, ) and % are not allowed in element ids or names.
Non-conforming characters in ids are likely to cause issues other than with jQuery. Using encodeURIComponent (e.g. to replace ( with %28) doesn't help because the % character isn't allowed either. But you can get away with character entities for letters outside the typical a-z,A-Z range, or you could just use plain old document.getElementById and if you really need to use jQuery:
may be sufficient (but not reliable).