开发者

Jquery .addClass('myclass') Then Selecting 'myclass' Isn't Working

I've got a couple divs with the class "listingThumb"

the CSS:

.listingThumb{
height:50px;
width:50px;
overflow:hidden;
}

the Html:

<div class="listingThumb"><img src="mypic.jpg"></div>

I want a user to be able to click that div and add a border that I have in another class that I add with .addClass()

.selectedThumb{
border:1px #f00 solid;
}

With this function:

$('.listingTh开发者_运维技巧umb').live('click',
    function(){
        $(this).addClass('selectedThumb');
    }
);

That all works fine and dandy. My problem is that I want the selected div to switch when a user clicks another div. So, what I do with my function is this...

$('.listingThumb').live('click',
    function(){
        $('.listingThumb').removeClass('selectedThumb'); // <-- remove any instance of that class...
        $(this).addClass('selectedThumb');
    }
);

But, any div that I've added 'selectedThumb' to via jquery doesn't register as having that class as it was added dynamically.

Is there a common solution for this?

Thanks -J


If you are looking for 'selectedThumb', why not search for it?

$('.selectedThumb').removeClass('selectedThumb');


There's nothing wrong with what you've provided...

See here for it working in jsfiddle link


You could try selecting specifically on the class you're removing:

$('.listingThumb').live('click',
    function(){
        $('.selectedThumb').removeClass('selectedThumb'); 
        $(this).addClass('selectedThumb');
    }
);

Although it really shouldn't make a difference. If you're having issues when selecting via listingThumb, I'd check spelling/capitalization first.


Your code should work, though this would make sure any element with that class would be removed:

$('.listingThumb').live('click',
    function(){
        $('.selectedThumb').removeClass('selectedThumb'); // <-- remove any instance of that class...
        $(this).addClass('selectedThumb');

    }
);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜