JQuery:将类添加到元素 - 不能将此类用于选择器



>我有以下问题:为了在不同情况下标记元素,我想向元素添加一个类:

jQuery('#menu-item-41 a').addClass('newsbox-closed1');

稍后,当单击带有此类的元素时,我想做一些有趣的工作人员 - 到目前为止它工作正常:

jQuery('.newsbox-closed1').click(function(){
      jQuery('#newsbox').css('display', 'block');
      jQuery(this).css('background-color', '#FF33AB').removeClass('newsbox-closed1').addClass('news-open');
 });

到目前为止,一切都很好。该元素获取类"新闻打开",如果出现新闻框。但是以下内容不再有效:

jQuery('.news-open').click(function(){
  alert('JUCVJU');
  jQuery(this).removeClass('news-open').addClass('newsbox-closed2');
  jQuery('#newsbox').css('display', 'none');
});

想法:当有人再次点击同一链接时,新闻框应该消失,链接会得到一个新的类。这不起作用 - 类"新打开"未删除,警报框未显示,什么都没有。此外,以下工作一半 - 它是新闻框上的关闭按钮:

jQuery('#close').click(function(){
  jQuery('#newsbox').css('display', 'none');
  jQuery('.news-open').removeClass('news-offen').addClass('newsbox-closed2')
});

ID 为"newsbox"的元素消失,但第二部分不起作用。类保留此元素。我没有收到任何错误消息,什么都没有...有谁知道什么会导致这种情况?

最好托比亚斯

您正在运行时添加类。改变

jQuery('.news-open').click(function(){

jQuery('.news-open').on('click',(function(){

以上是针对 JQuery>=1.7

对于 JQuery <1.7,请使用

jQuery('.news-open').live('click',function(){

在 JQuery 中也为运行时创建的元素工作。

您可能需要委托事件处理程序,因为您要在文档加载后更改类。尝试替换

jQuery('.news-open').click(function(){

jQuery(document).on('click', '.news-open', function(){

但是,如果您可以使其比document更具体,那么您应该这样做。将事件委托给最近的.news-open容器,以获得最佳效率。

http://api.jquery.com/on/

谢谢你们!!

为了给其他面临类似问题的其他人带来这一点,我的工作代码如下所示:

jQuery('#menu-item-41').on('click', '.news-open', (function(){
  alert('JUCVJU');
  jQuery(this).removeClass('news-open').addClass('newsbox-closed2');
  jQuery('#newsbox').css('display', 'none');
}));
id ">

menu-item-41" 是容器的 id,它用类 "news-open" 包围我的元素。现在,当我再次单击进一步重新分类的元素时,我会收到警报框,新闻框消失了。

非常相似的问题:在单击链接时,我制作一个动画来显示隐藏的div,并将'.hideMe'类添加到布局的其余部分,以便单击显示的div 的任何地方都会再次隐藏它。 '.hideMe'不能被jQuery选择,因为它在页面加载时不存在。 通过委派将两个.on()方法链接在一起来解决,如下所示:https://stackoverflow.com/a/8261148

$(document.body).on('click', '#link', function() {
  $('div').addClass('.hideMe').animate(); // animation code here
  $('#newdiv').show();
}).on('click', '.hideme', function() {
  $('div').removeClass('.hideMe').animate(); // animation code here
  $('#newdiv').hide();
});

这是jQuery 1.10.x。

最新更新