2011-05-02 25 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) 
相關問題