【问题标题】:div with the id="(name)" can I use this or not? [duplicate]带有 id="(name)" 的 div 我可以使用它吗? [复制]
【发布时间】:2013-09-14 04:10:28
【问题描述】:

我可以在 jquery mobile 中将 id 与 "("")" 一起使用吗?

例如:

<div id="RSI(3,4)">
</div>

我已经尝试过那个 id 并且想在 js 中访问那个元素。

$("#RSI(3,4)").html("some text");

但是没有用。

【问题讨论】:

标签: javascript jquery html jquery-mobile


【解决方案1】:

转义特殊字符

$("#RSI\\(3\\,4\\)").html("some text");

http://api.jquery.com/category/selectors/

使用任何元字符(例如 !"#$%&'()*+,./:;?@[\]^`{|}~ )作为名称,必须用两个反斜杠转义:\\。例如,id="foo.bar" 的元素可以使用选择器 $("#foo\\.bar")。

也就是说,关于在 ID 中使用特殊字符的有效性,一些验证器会抱怨,我当然不建议在 ID 中使用任何特殊字符,也不建议使用前导数字,因为您可以根据最新的 html 规范。让您的生活更轻松,仅使用 a-zA-Z0-9,如果需要,请下划线

【讨论】:

  • 很有意思,不知道这个!你知道这个的使用是否有限制吗?例如浏览器不兼容等?
  • @BenM 不应该有任何跨浏览器兼容性问题,因为 jQuery 的目标是与浏览器无关。如果有的话,它可能是一个 jQuery 错误。
  • 只有验证者应该抱怨,我当然不建议在 ID 中使用任何特殊字符,也不建议使用前导数字,因为您可以根据最新的 html 规范。使用 a-zA-Z,如果需要,下划线
  • 这段代码不工作
  • 使用了这个 $("#RSI\(3\\,4\)").html("some text");
【解决方案2】:

W3C Validator 说这个 html 代码

<html>
<head>
    <title>TITLE</title>
</head>
<body>
    <div id="RSI(3,4)"></div>
</body>
</html>

对 html5 有效,但对 html4.01 Strict 无效,(id 属性中的无效字符。 http://validator.w3.org/check

在 jQuery 中,您必须使用 \\ 转义它们

http://api.jquery.com/category/selectors/

【讨论】:

    【解决方案3】:

    你能检查一下这个jsfiddle

    $(document).ready(function() {
    $("#RSI\\(3\\,4\\)").html("some text");
    });
    

    工作正常

    【讨论】:

    • 感谢您指出逗号也需要转义
    猜你喜欢
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多