开发者

Can't show the element when its class or id contains dots

I must have class 开发者_开发技巧which contains dots, but then jQuery doesn't work. What should I do? Example: http://jsfiddle.net/9KYmx/

<div style="display: none" class="dfv.png">
    text
</div>
$(document).ready(function() {
    $('.dfv.png').show();
})

P.S. ID also doesn't work.


You need to escape them. From the manual:

If you wish to use any of the meta-characters 
( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) 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"). 


If your selector is constant, you have to escape dots with backslash (\), So you should do:

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

But, a more general solution is to auto-escape special characters. You could escape all special characters with the Ian McKellar's escape plugin, the code is short:

//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));
}
})();

So you do:

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

Hope this helps. Cheers


You need to escape the .:

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


A . character indicates the start of a class selector, so you need to escape it.

The CSS escape character, \ is also an escape character in JS, so you need to escape it too.

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


You need to escape the dot in the class name.

Try this:

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

Working example: http://jsfiddle.net/9KYmx/1/


you can do this:

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


in my use case, the class wasn't known till run time

simple regex replace worked fine

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

to test:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜