使用jQuery处理元素ID中的冒号

Ami*_*ngh 142 jquery

我们无法使用jQuery在JS代码中访问ID为"test:abc"的div元素.

<div id="test:abc">

$('#test:abc') 
Run Code Online (Sandbox Code Playgroud)

没有结肠,它工作正常.我们无法控制ID生成,因为它是在Trinidad子表单中自动生成的,因为它将子表单ID附加:到其中的每个元素.

nfe*_*ner 199

你需要使用两个反斜杠来逃避冒号:

$('#test\\:abc')
Run Code Online (Sandbox Code Playgroud)


Tos*_*kan 84

简而言之

$(document.getElementById("test:abc")) 是你应该使用的.

说明:除了速度增益(见下文)外,它更容易处理.

示例:假设您有一个功能

   function doStuff(id){

       var jEle = $("#" + id); //is not safe, since id might be "foo:bar:baz" and thus fail. 
       //You would first have to look for ":" in the id string, then replace it

       var jEle = $(document.getElementById(id)); //forget about the fact 
      //that the id string might contain ':', this always works
    }

    //just to give an idea that the ID might be coming from somewhere unkown
    var retrievedId = $("foo").attr("data-target-id");
    doStuff(retrievedId); 
Run Code Online (Sandbox Code Playgroud)

速度/计时

看看这个jsbin,它测试并比较ID与冒号的选择方法的速度

你需要打开你的firebug控制台来获得结果.

我用firefox 10和jquery 1.7.2测试了它

基本上我做了一个选择10'000次div的id冒号 - 用不同的方法来实现它.然后我将结果与没有冒号的ID选择进行比较,结果非常令人惊讶.

在ms右选择器方法中剩余时间

299 $("#annoying\\:colon")

302 $("[id='annoying:colon']"

20 $(document.getElementById("annoying:colon"))


71 $("#nocolon")

294 $("[id='nocolon']")
Run Code Online (Sandbox Code Playgroud)

特别

  71 $("#nocolon") and
299 $("#annoying\\:colon")
Run Code Online (Sandbox Code Playgroud)

有点意外

  • 简单地使用更复杂的代码来存档相同的结果只是因为它更快是一个过早优化的情况.除非是性能瓶颈,否则你应该总是喜欢可读代码而不是快速代码.或者用[Wiliam Wulf](http://en.wikipedia.org/wiki/William_Wulf)的话来说:"更多的计算罪行以效率的名义(不一定实现它)而不是任何其他单一原因 - 包括盲目的愚蠢." 更多信息[这里](http://en.wikipedia.org/wiki/Program_optimization). (4认同)
  • 这非常有用,应该更多.尽管如此,$("[id ='恼人:冒号']"仍然有效.document.getElementById似乎应该被使用. (3认同)
  • 对于更新的jQuery(2.1.1)似乎更好:**32**`$("#annyoing \\:冒号")`,**29**`$("[id ='annyoing:冒号'] ")`,**5**`$(document.getElementById("annyoing:冒号"))`,**8**`$("#nocolon")`,**31**`$("[ ID = 'nocolon']")` (3认同)

tva*_*son 29

显然,它在冒号上绊倒,因为jQuery试图将其解释为选择器.尝试使用id属性选择器.

 $('[id="test:abc"]')
Run Code Online (Sandbox Code Playgroud)


wsa*_*lle 8

我会使用document.getElementById,并将结果传递给jQuery()函数.

var e = document.getElementById('test:abc');
$(e) // use $(e) just like $('#test:abc') 
Run Code Online (Sandbox Code Playgroud)


diE*_*cho 7

使用两个反斜杠 \\

DEMO

如此处所写

如果你想使用任何元字符(例如!"#$%&'()*+,./:; <=>?@ [] ^`{|}〜)作为字面的一部分name,你必须用两个反斜杠转义字符:\.例如,如果你有一个id ="foo.bar"的元素,你可以使用选择器$("#foo\.bar").W3C CSS规范包含完整的

参考