开发者

Why is jQuery adding a space to the class attribute?

I'm having some strange issues with .removeClass() and .addClass() in jQuery.

Specifically it seems that when I use .removeClass() the class is indeed removed, but a single space is left in it's place. then when I .addClass("secondclass") I get class=" secondclass" (with the space in front).

I'm using jQuery 1.4.1

Is this intended behaviour or a bug? How to stop it?

UPDATE:

Some people have asked what problems this is causing. Well, I'm using thins:

$("img.somecla开发者_运维问答ss").click(function() {

I'm testing this with Firefox 3.6.3

Which does not trigger with the space in front of the class name. When I manually remove the space it works fine. It seems that there is more too this problem than the space issue, and most likely the space wasn't causing any issues (glad it's gone though ;) - Will post seperate question regarding the ongoing issue.


Because multiple classes are delimeted by spaces:

<div class="class1 class2 class3">...</div>

It's easier to add a space rather than code in special conditions. In the above you can simply replace "class3" with "" if you want to remove it, changing it to:

<div class="class1 class2 ">...</div>

Otherwise you need to worry about whether it's the first class or not as to whether to leave a class there. Plus your markup may be putting multiple spaces there (deliberately or inadvertently) anyway.


this is the bug in jQuery version 1.4.1, but this is fixed in jQuery version 1.4.2. If you want to stop this behavior, you can use the latest version.


It's because jQuery is a poorly coded library and shouldn't be used anyway. Here, I've written another pair that actually works:

function addClass(node, name) {
  node.className += (node.className ? ' ' : '') + name;
}
function removeClass(node, name) {
  node.className = node.className.
    split(' ' + name).join('').
    split(name).join('');
}


@cletus explained it but you can use JQuery's $.trim function to remove the spaces too although I am not sure why you want to do that:

$('selector').attr('class', $.trim($('selector').attr('class'));

Update:

You can do like this:

var class = $('selector').attr('class', $.trim($('selector').attr('class'));

$("img." + class).click(function() {
  // your code......
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜