jQuery:将类添加到元素-无法将此类用于选择器? [英] JQuery: add class to element - cannot use this class for selector?
问题描述
我有以下问题:为了在不同情况下标记一个元素,我想向该元素添加一个类:
I have the following problem: in order to mark an element during different situation I want to add a class to the element:
jQuery('#menu-item-41 a').addClass('newsbox-closed1');
稍后,当我单击此类的元素时,我想做一些有趣的工作-到目前为止,它可以正常工作:
Later I want to do some funny staff when the element with this class is clicked - so far it works fine:
jQuery('.newsbox-closed1').click(function(){
jQuery('#newsbox').css('display', 'block');
jQuery(this).css('background-color', '#FF33AB').removeClass('newsbox-closed1').addClass('news-open');
});
直到现在一切都还好.元素获得"news-open"类,并且出现新闻框.但是,以下内容将不再起作用:
Until now everything is just fine. The element gets the class "news-open" andf the newsbox appears. But then the following does not work anymore:
jQuery('.news-open').click(function(){
alert('JUCVJU');
jQuery(this).removeClass('news-open').addClass('newsbox-closed2');
jQuery('#newsbox').css('display', 'none');
});
想法:当某人再次单击同一链接时,新闻框应消失,并且该链接将获得一个新的类.这不起作用-没有删除新打开"类,没有显示警报框,什么也没有. 此外,以下工作已完成一半-这是新闻框上的关闭按钮:
Idea: when someone clicks on the same link again, the newsbox should disappear and the link gets a new class. This does not work - the class "new-open" is not removed, the alertbox is not shown, nothing. Additionally the following work half the way - it is a close button on the newsbox:
jQuery('#close').click(function(){
jQuery('#newsbox').css('display', 'none');
jQuery('.news-open').removeClass('news-offen').addClass('newsbox-closed2')
});
标识为"newsbox"的元素消失,但第二部分无效.该类保留此元素.我没有收到任何错误消息,没有任何消息...没人知道会导致这种情况的原因吗?
The element with id "newsbox" disappears but the second part has no effect. The class remains of this element. I get no error messages, nothing... does anyone has an idea what can cause this?
最好, 托比亚斯
推荐答案
您正在在运行时添加类.更改
You are adding class at runtime. Change
jQuery('.news-open').click(function(){
到
jQuery('.news-open').on('click',(function(){
以上是针对JQuery> = 1.7
Above is for JQuery >=1.7
对于JQuery< 1.7,请使用
For JQuery <1.7, use
jQuery('.news-open').live('click',function(){
在JQuery中实时运行也适用于在运行时创建的元素.
live and on in JQuery work for elements created at runtime too.
这篇关于jQuery:将类添加到元素-无法将此类用于选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!