【问题标题】:Selecting an ID with a colon in it with jQuery使用 jQuery 选择带有冒号的 ID
【发布时间】:2011-09-15 16:25:37
【问题描述】:

我正在为一个网站编写一个预先编写的模块,我需要定位一个 ID 为 test:two 的元素。现在,这个元素中有一个冒号,所以 jQuery 将“two”视为一个伪类可能是可以理解的。有没有办法用 jQuery 来定位这个元素?

此外,无法更改 ID。相信我,如果可以的话,我会的。

我整理了一个例子:

$('#test').css('background','red');
$(document.getElementById('test:two')).css('background','blue');
$('#test:two').css('background','green');
<script src="//code.jquery.com/jquery-1.6.3.js"></script>

<div id="test">test</div>
<div id="test:two">test two</div>

【问题讨论】:

标签: javascript jquery identifier colon


【解决方案1】:

只需使用\\ 转义冒号:

$('#test\\:two');

http://jsfiddle.net/zbX8K/3/


请参阅文档:How do I select an element by an ID that has characters used in CSS notation?

【讨论】:

    【解决方案2】:

    来自the jQuery ID Selector docs

    如果 id 包含句点或冒号等字符,则必须escape those characters with backslashes

    因为反斜杠本身需要在字符串中转义,所以您需要这样做:

    $("#test\\:two")
    

    $('#test').css('background','red');
    $(document.getElementById('test:two')).css('background','blue');
    $('#test\\:two').css('background','green');
    <script src="//code.jquery.com/jquery-1.6.3.js"></script>
    
    <div id="test">test</div>
    <div id="test:two">test two</div>

    您现在还可以选择使用内置的 CSS.escape(...) 函数,该函数负责处理选择器表达式中可能具有特殊含义的任何字符。

    $("#" + CSS.escape("test:two"))
    

    $('#test').css('background','red');
    $(document.getElementById('test:two')).css('background','blue');
    $("#" + CSS.escape("test:two")).css('background','green');
    <script src="//code.jquery.com/jquery-1.6.3.js"></script>
    
    <div id="test">test</div>
    <div id="test:two">test two</div>

    【讨论】:

      【解决方案3】:

      使用attribute equals selector

      $('[id="test:two"]')
      

      【讨论】:

      • 我的猜测是这会比接受的答案更差。知道是不是这样吗?
      • @Kip:可能只是另一个建议。
      • 谢谢,有帮助。
      【解决方案4】:

      尝试使用属性选择器

      $(document).ready(function() {
          $('div[id="test:two"]').each(function() {
             alert($(this).text());
          }); 
      });
      

      小提琴:http://jsfiddle.net/zbX8K/2/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-23
        • 1970-01-01
        • 2011-10-21
        • 2012-01-19
        • 1970-01-01
        • 2011-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多