2011-05-02 91 views

回答

3

如果你的选择是固定的,你必须转义反斜杠(\)点,那么你应该做的:

$('.dfv\\.png').show(); 

但是,更通用的解决方案是自动转义特殊字符。 你能逃脱与Ian McKellar's escape plugin所有特殊字符,代码简称:

//Just copy and paste this 
(function() { 
escape_re = /[#;&,\.\+\*~':"!\^\$\[\]\(\)=>|\/\\]/; 
jQuery.escape = function jQuery$escape(s) { 
    var left = s.split(escape_re, 1)[0]; 
    if (left == s) return s; 
    return left + '\\' + 
    s.substr(left.length, 1) + 
    jQuery.escape(s.substr(left.length+1)); 
} 
})(); 

所以你做的事:

$(document).ready(function() { 
    var your_selector = "dfv.png"; //your_selector can be variable 
    $("."+$.escape(your_selector)).show(); 
}); 

希望这有助于。 干杯

在我的使用情况
+0

上帝保佑你!!!!有一个伟大的人生! – 2011-05-02 19:19:43

+0

Thaks很多!你也是。欢呼声,来自玻利维亚的拉巴斯 – 2014-01-12 00:41:23

4

你需要逃避它们。从the manual:

If you wish to use any of the meta-characters 
(such as !"#$%&'()*+,./:;<=>[email protected][\]^`{|}~) as a 
literal part of a name, you must escape the character 
with two backslashes: \\. For example, if you have an 
element with id="foo.bar", 
you can use the selector $("#foo\\.bar"). 
1

你需要躲避.

$(document).ready(function() { 
    $('.dfv\\.png').show(); 
}) 
+0

类定义了,我无法逃避。是否有可能在jQuery中使用像在PHP str_replace smth?然后我会用\替换点。 – 2011-05-02 18:56:03

+0

@hey你是什么意思? – Neal 2011-05-02 18:56:47

+0

类给出。然后我把它放在数组中,如'info ['id']',它等于'dfv.png'。然后我需要使用jQuery函数创建'dfv \\。png',如果有的话。 – 2011-05-02 18:58:08

1

一个.字符指示类选择的开始,所以你需要逃避它。

CSS转义字符\也是JS中的转义字符,因此您也需要将其转义。

$('.dfv\\.png').show(); 
0

,你可以这样做:

$(document).ready(function() { 
    $('.dfv\\.png').show(); 
}); 
0

,类并不知道,直到运行时

简单的regex顶替工作的罚款

var selectorEscaped = 'bo.selecta.shamone'.replace(/\./g, '\\.'); 

测试:

$('body').append('<div class="bo.selecta.shamone"/>'); 
var selectorEscaped = 'bo.selecta.shamone'.replace(/\./g, '\\.'); 
$('.' + selectorEscaped)